最近每月一次的服务器log备份比较郁闷。今天终于写了个脚本来实现,用crontab来调用。解脱了。
废话不说了。代码如下:
#!/usr/bin/python
# Descript: Auto Backup logs.
from datetime import datetime,timedelta
import os,sys,string,socket
import smtplib
refmonth = 2;
now = datetime.now();
year = now.year;
month = now.month;
day = now.day;
# define the year and month for backup
if month > refmonth:
backupyear = str(year);
backupmonth = month - refmonth;
else:
backupyear = str(year-1);
backupmonth = 12 + month - refmonth;
#add the str '0' if the month is less than 10
if backupmonth < 10:
backupmonth = "0" + str(backupmonth);
else:
backupmonth = str(backupmonth);
#print str(backupyear)+"/"+backupmonth+"/"
res = os.popen("ps -ef | grep /usr/bin/postmaster | grep -v grep | wc -l").readlines();
#print res[0];
# detect if the host is active
if int(res[0]) == 1 :
#detect if the day is the first one of the month
if day == 1:
flag = os.system("mount -t nfs 1.1.1.1:/vol/***/ /log");
if int(flag) == 0:
os.system("mkdir -p /log/***/"+backupyear+"/");
if int(os.system("tar -C /var/log/***/"+backupyear+"/ -zcvf /log/***/"+backupyear+"/"+backupmonth+".tar.gz "+backupmonth+"/")) == 0:
if int(os.system("gpg --passphrase *** -c /log/***/"+backupyear+"/"+backupmonth+".tar.gz")) == 0:
os.system("rm -rf /log/***/"+backupyear+"/"+backupmonth+".tar.gz");
os.system("rm -rf /var/log/***/"+backupyear+"/"+backupmonth+"/")
os.system("umount /log");
else:
smtp = smtplib.SMTP('mx.***.com')
smtp.set_debuglevel(1)
msg = '''From: God@***.com\r\nSubject: God die\r\nTo:Evil@***.com\r\n\r\n Mount 1.1.1.1 failed\r\n'''
smtp.sendmail("God@***.com", "Evil@***.com", msg)
smtp.quit()
然后去crontab里面调用一下,每月1号执行。搞定。
ps:中间碰到一个问题,mount的时候一直超时而且返回失败,但是实际是mount成功的。后面咨询同学后了解portmap没启动造成的。
service portmap start
chkconfig portmap on
收工,闪人。
#1