python结合shell写的日志备份脚本

用于压缩打包一个月前一周的日志文件,并上传至FTP服务器保存,以目录名为参数。 如:/usr/local/bin/log_backup.py /usr/local/apache/logs/accesslog/ /usr/local/tomcat/logs/

#!/usr/bin/python
# -*- #coding:cp936

import os
import sys
import time
import datetime
from ftplib import FTP

def getip():
    #cmd3 = "/sbin/ifconfig eth0 |grep \"inet addr:\" |awk \'{print $2}\'|cut -c 6-"
    cmd3 = "ifconfig|grep 'inet addr'|grep Bcast|grep -v '192.168'|awk '{print $2}'|cut -c 6-"
    ip = os.popen(cmd3).read().rstrip()
    #iplist=ip.split('.',4)
    #fileip=iplist[3]
    return ip

def ftp(bakfile):
    ftp=FTP()

    ftp.set_debuglevel(2)
    ftp.connect('192.168.0.1','21')
    ftp.login('user','pass')

    ftp.cwd('log_bak')
    bufsize = 1024
    file_handler = open(bakfile,'rb')
    ftp.storbinary('STOR %s' % os.path.basename(bakfile),file_handler,bufsize)
    ftp.set_debuglevel(0)

    file_handler.close()
    ftp.quit()

def main(dirname):

    stamp = datetime.datetime.now().strftime('%Y%m%d')
    tarname = dirname + getip() + dirname.replace('/','_') + str(stamp) + ".tar.gz"
    tarcmd = "tar -zcvf " + tarname + " $(find " + dirname + " -maxdepth 1 -type f -mtime +30 -mtime -38 -name '*.log*' -o -name '*.txt*'|sort)"
    os.system(tarcmd)
    print os.system(tarcmd)
    if os.system(tarcmd) == 0:
        rmcmd = "find " + dirname + " -maxdepth 1 -type f -mtime +30 -mtime -38 -name '*.log*' -o -name '*.txt*'|xargs rm -f {}"
        #print rmcmd
        #os.system(rmcmd)
    else:
        print "Process error"
        sys.exit(0)


if len(sys.argv) < 2:
    print 'Error: One parameter at least!!!'

print sys.argv[1:]
for dirname in sys.argv[1:]:
    print dirname
    main(dirname)

发表评论

电子邮件地址不会被公开。 必填项已用*标注