适用环境:在服务器中经常会备份我们服务器的日志,以备不时之需。下面脚本可以基本上完全满足我们的需求。find_bak_files用于搜索我们的日志。下面脚本以httpd为例子
#!/usr/bin/python3
# -*- conding: UTF-8 -*-
import tarfile
import time
import fnmatch
import os
import sys
def find_bak_files(root='/var/log/httpd'):
formats=['access*log*']
file_bak=[]
for root,dirname,filenames in os.walk(root):
for extensions in formats:
for filename in fnmatch.filter(filenames,extensions):
file_bak.append(os.path.join(root,filename))
return file_bak
def check_bak(filename):
with tarfile.open(filename) as f:
for member_info in f.getmembers():
return member_info.name
def main():
now=time.strftime("%Y%m%d%H%M%S")
sys.argv.append('')
bak_directory=sys.argv[1]
bak_filename='/bak/apache-log-{0}.tar'.format(now)
with tarfile.open(bak_filename,mode='w') as bak:
for log in find_bak_files():
bak.add(log)
if check_bak(bak_filename):
print('The backup successful.Backup filename is{0} :'.format(bak_filename))
if find_bak_files():
print('backup files is:{0}'.format(find_bak_files()))
if __name__ == '__main__':
main()