定时执行备份 分类: python 小练习 ubuntu 2014-03-19 14:34 224人阅读 评论(0) 收藏

CentOS 操作系统

1.编写备份程序

2.使用crontab命令,定时执行备份程序

步骤一:

编写备份文件bak.py:

#coding:utf-8

import os
import time
source=["/root/","a.py"]
#目标目录
targetdir="/root/backup/"
#目标目录下的当天日期
today = targetdir+time.strftime("%Y%m%d")
now = time.strftime("%H%M%S")
#如果目标目录不存在以当天日期命名的目录,则创建
if not os.path.exists(today):
    os.makedirs(today)
    print "create dir ok!!"
targe = today+os.sep+now+".zip"
print targe
#备份
comm = "zip -qr %s %s" %(targe,"".join(source))
if os.system(comm)==0:
    print "backup ok...",targe
else:

    print "backup failed"

步骤二:

使用crontab -e编辑定时任务:

#! /bin/sh
*/20 * * * * python /root/bak.py

每20分钟执行py程序。

service crond restart 重启定时服务

步骤三:

查看后台日志:

tail -f /var/log/cron



定时执行任务结果:



版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/think1988/p/4627919.html