iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python常用的备份脚本
  • 953
分享到

python常用的备份脚本

脚本备份常用 2023-01-31 05:01:58 953人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

脚本介绍:1)备份源目录的文件2)目标文件以tar 和bzip2的方式压缩之后放在当前日期文件夹下4)备份文件以时间注释和执行脚本的用户命名3)主要用到了时间模块,系统模块,和getpass模块4)source 可以修改为想备份的目录,因为

脚本介绍:

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 \;


--结束END--

本文标题: python常用的备份脚本

本文链接: https://www.lsjlt.com/news/189232.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作