您的位置:首页 > 编程语言 > Python开发

python常用的备份脚本

2017-08-14 00:00 141 查看
脚本介绍:

1)备份源目录的文件

2)目标文件以tar 和bzip2的方式压缩之后放在当前日期文件夹下

4)备份文件以时间注释和执行脚本的用户命名

3)主要用到了时间模块,系统模块,和getpass模块

4)source 可以修改为想备份的目录,因为备份目录一般不经常变动,所以这里写死了

#!/bin/env python
import os
import time
import getpass
source = ['/data/mysql', '/data/mysql/mysql']
target_dir = '/backup/'
user = getpass.getuser()
today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
comment = raw_input('please input comment --> ')
if len(comment) == 0:
target = today + now + '_' + user + '_' + 'tar.bz2'
else:
target = today +  now + '_' + comment + '_' + user + '_' + 'tar.bz2'
if not os.path.exists(today):
os.mkdir(today)
print 'Create folder successfully', today
else:
print today,'Folder already exists'
time.sleep(5)
zip_command = "tar -cjPf '%s' %s" % (target, ' '.join(source))
if os.system(zip_command) == 0:
print ' Backup for success:', target
else:
print 'Backup for failed' ,target


备注:一下是详细解释:

#!/bin/env python
#告诉解释器查找pyton解释器并且使用它
#_*_encoding:utf8_*_
#指定编码为utf8编码
import os
#导入系统模块
import time
#导入时间模块
import getpass
#导入获取用户模块
source = ['/data/mysql', '/data/mysql/mysql']
#定义备份源目录
target_dir = '/backup/'
#定义备份目标目录
user = getpass.getuser()
#定义使用备份脚本的用户
today = target_dir + time.strftime('%Y%m%d')
#定义今日的日期
now = time.strftime('%H%M%S')
#定义现在的时间
comment = raw_input('please input text --> ')
#定义注释为输入的字符串
if len(comment) == 0:
#检查输入的注释是否为空
target = today + now + '_' + user + '_' + 'tar.bz2'
#如果注释为空,备份文件的文件名为日期时间运行脚本用户
else:
target = today +  now + '_' + comment + '_' + user + '_' + 'tar.bz2'
#如果非空,则使用日期时间注释用户为文件名
if not os.path.exists(today):
#检查备份目录下的时间目录是否不存在

os.mkdir(today)
#如果不存在创建文件夹
print 'Create folder successfully', today
else:
#存在,则打印
print today,'Folder already exists'
time.sleep(5)
#暂停五秒
zip_command = "tar -cjPf '%s' %s" % (target, ' '.join(source))
#定义本备份命令

if os.system(zip_command) == 0:
#使用系统环境(相当于shell执行备份命令,如果成功返回0)
print ' 成功备份为:', target
else:
print '备份失败' ,target


2,查找某个目录下N天以前的以log结尾的文件并移动到/tmp下

[root@zabbix log]# find /data/nginx/log  -type f -name "*.log" -mtime +114 -exec mv {} /tmp \;


本文出自 “清风明月” 博客,请务必保留此出处http://liqingbiao.blog.51cto.com/3044896/1749996
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python