python--- 備份日誌(待優化)
阿新 • • 發佈:2019-02-17
root@kali:~/python/log# ls
account.log backup.log ext.txt logback.py logger.py logger.pyc
root@kali:~/python/log# cat ext.txt
/root/python/atmnew/account.pkl
/root/python/atmnew/logger.pyc
/root/python/atmnew/logger.py
root@kali:~/python/log# cat logback.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
import sys,os,time,logger
source_file = sys.argv[1 ]
formated_source_file = source_file.split('/')[-1]
backup_dir = '/root/python/atmnew'
backup_to_file = '''%s%s_%s.tgz''' % (backup_dir,formated_source_file,time.strftime("%Y-%m-%d_%H%M%S",time.localtime()))
def run_backup(runtime="now",exclude_file_name = 'None'):
if len(sys.argv) == 4:
print '-------exclude file mode-------------'
if sys.argv[2] == '-X':
exclude_file_name = sys.argv[3]
backup_cmd = 'tar cvzfX %s %s %s ' %(backup_to_file,exclude_file_name,source_file)
else:
print '------------Normal mode----------------'
#backup_cmd = 'tar cvzf %s %s | wc -l' %(backup_to_file,source_file)
backup_cmd = 'tar cvzf %s %s' %(backup_to_file,source_file)
run_command = os.system(backup_cmd)
if run_command == 0:
logger.record_log('Full Backup','Success','N/A','test')
else:
logger.record_log('Full Backup','Failure','N/A','test')
run_backup()
root@kali:~/python/log# cat logger.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
import time#匯入時間模組
logfile = 'backup.log'#定義要使用的日誌檔案account.log
#定義函式包括引數賬戶、花費、描述資訊、利息(預設為0、取款、轉賬有手續費必須帶引數值)
def record_log(Backup_type,Status,files,description = 'NULL'):
date = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())#取出當前時間
record_line = "%s %s '%s' %s %s\n" %(date,Backup_type,Status,files,description)#記錄當前消費時呼叫函式各個引數時間行為
f = open(logfile,'a')#追加寫入方式開啟日誌account.log
f.write(record_line)#寫入每行函式產生日誌資訊
f.flush()#實時寫入
f.close()#關閉檔案
root@kali:~/python/log# cat backup.log
2017-06-13 23:46:45 Full Backup 'Success' N/A test
2017-06-13 23:59:34 Full Backup 'Success' N/A test
root@kali:~/python/log#
執行:
root@kali:~/python/log# cat backup.log
2017-06-13 23:46:45 Full Backup 'Success' N/A test
root@kali:~/python/log# vi ext.txt
root@kali:~/python/log# vi logback.py
root@kali:~/python/log# python logback.py /root/python/atmnew -X ext.txt
-------exclude file mode-------------
tar: 從成員名中刪除開頭的“/”
/root/python/atmnew/
/root/python/atmnew/account.py
/root/python/atmnew/record_account.py
/root/python/atmnew/account.log
/root/python/atmnew/pickle_test.py
/root/python/atmnew/::wq
root@kali:~/python/log# cat ext.txt
/root/python/atmnew/account.pkl
/root/python/atmnew/logger.pyc
/root/python/atmnew/logger.py
root@kali:~/python/log#
root@kali:~/python# ls atmnew
account.log account.pkl account.py logger.py logger.pyc pickle_test.py record_account.py ::wq
root@kali:~/python# ls
atmnewaccount.py_2017-06-13_234645.tgz
atmnewatmnew_2017-06-13_235934.tgz
root@kali:~/python#