数据备份crontab+pyhon

数据备份文档


描述:
定时备份数据到新硬盘中,这个是在同一个系统中.如果是通过网络备份到另一台服务器上,则可以用简单软件即可


细节:
crontab+python/shell


功能:
~定时备份指定文件夹中的文件到新硬盘中,时间可达到1分钟
~当文件夹中有修改,增加,减少时,新硬盘都会跟着一起更新(每隔一定时间)


步骤:


1. 挂载硬盘到/mnt/bittorrent文件夹下
~fdisk -l 
~fdisk /dev/sdb进入分区命令
m帮助
n新建
~w写入并退出
~格式化硬盘
~mkfs.ext3 /dev/sdb1对刚刚的主分区格式化
输入信息就输入done
~mount挂载


2. 更改bittorrent文件属性
chmod o+w /mnt/bittorrent
chmod 777 /mnt/bittorent也行


3.编写python文件
backups.py


python中的变量说明:
~pwd_back是备份路径 /mnt/bittorrent/可更改
~interver_time是间隔时间,这个需要与crontab中时间间隔一致,单位是s


chmod +x backups.py
这个文件要放到源文件夹中,如果要更改路径,则程序要稍作修改


4. 设置crontab
~crontab -e
~选择一个编辑器,选2
在最后一行加入:
# m  h  dom  mon  dow command
  0  *   *    *    *  /home/wen/test/src/backups.py
  分 时  日  月 周 命令
  0~59 0~23 1~31 1~12 0~7
  若为*则表示每
  */6 表示乘以
这个命令就是你的python,到时自动执行这个
~sudo /etc/init.d/cron restart
~crontab -r删除所有任务
~
~查看任务crontab -l 
一般这里没任务,不知道是为什么


也可以直接编辑/etc/crontab文件,按里面的格式添加,如:
* * * * * wen   cd /home/wen/test/src/ && ./backups.py 


backups.py:

#!/usr/bin/env python
# coding=utf-8
import os
import time
import os.path

pwd_back     = '/home/wen/test/back/'
pwd          = os.getcwd()
bak_contents = os.listdir(pwd_back)
src_contents = os.listdir(pwd)

#暂定为60s
interver_time = 60 
now_time      = time.time()
#算法:当前时间减去crontab的时间与修改时间比较
#如果修改时间小,则表明这个文件有修改,就要备份, 否则不备份
for files in src_contents:
    if files not in bak_contents or now_time - os.path.getatime(files) < interver_time:
        os.system("cp -f %s %s" % (files,pwd_back))
        print 'cp '+files+' to back'
        print '#'*40

for file in bak_contents:
    if file not in src_contents:
        os.system("rm -f %s" % pwd_back+file )
        print 'rm '+file+' from back'
        print '#'*40





  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值