备份配置文件的python脚本

Python/PHP/Perl 开发与设计
回复
头像
roylez
论坛版主
帖子: 1928
注册时间: 2005-10-04 10:59
来自: 上海
送出感谢: 0
接收感谢: 1 次

备份配置文件的python脚本

#1

帖子 roylez » 2007-01-30 16:56

参考了ee关于tar用法的帖子。写得不好大家别怪。
trackback.php?e=1288

使用前先修改程序开头的备份文件路径。
cfgbackup [option][files...]
-l 查看已经备份的文件列表同修改时间
-h 看帮助
-u 更新所有的备份
-r 恢复所有文件
不带参数即为把文件加入备份列表。

代码: 全选

#!/usr/bin/env python
import os.path, os, tarfile

backup_file='/home/roylez/.backup/config/bkcfg.tar'

class FileBackup:
    def __init__(self, bkupfile=None):
	self.bkupfile = bkupfile
    
    def backup(self, newfiles):
	files = self.members().split()
	oldfile = []
	tf = tarfile.open(self.bkupfile,'r')
	for file in files:
	    if not os.path.exists(file):
		print '%s does not exist, skipped.' %file
	    elif tf.getmember(file).mtime < os.path.getmtime(file) and \
		    file not in oldfile:
		oldfile.append(file)
	tf.close()
	if oldfile != []:   
	    self.delete(oldfile)
	cmd = 'tar uPvfh %s %s' %(self.bkupfile, ' '.join(oldfile))
	self._runandmodifymsg(cmd,' \033[32mupdated\033[m in the archieve.')
	self.append(newfiles)

    def restore(self):
	cmd = 'tar xPvf %s' %(self.bkupfile)
	self._runandmodifymsg(cmd, ' \033[34mrestored\033[m.')

    def append(self, files):
	flist = []
	if os.path.isfile(self.bkupfile):
	    tf = tarfile.open(self.bkupfile,'r')
	    for file in files:
		if os.path.isfile(file) and \
			os.path.abspath(file) not in tf.getnames():
		    flist.append(file)
	    tf.close()
	else:
	    flist = files
	fl = ' '.join([os.path.abspath(file) for file in flist])
	cmd = 'tar uPvfh %s %s' %(self.bkupfile, fl)
	self._runandmodifymsg(cmd,' \033[31mappend\033[m.')

    def delete(self, files):
	files2 = []
	for file in files:
	    absf = os.path.abspath(file)
	    if self._inarchive(absf):
		files2.append(absf)
	    else:
		print '%s not in the archieve!' %(absf)
	fl = ' '.join(files2)
	cmd = 'tar --delete -f %s %s' %(self.bkupfile, fl)
	os.system(cmd)
	for file in files2:
	    print '%s \033[33mdeleted\033[m from achieve.' %os.path.abspath(file)
    
    def extract(self, files):
	tf = tarfile.open(self.bkupfile,'r')
	for file in files:
	    absf = os.path.abspath(file)
	    if self._inarchive(absf):
		tf.extract(file)
		print '%s \033[35mextracted\033[m.' %file
	    else:
		print 'Please use absolute path to extract %s.' %file
	tf.close()

    def members(self):
	cmd = 'tar tf %s' %(self.bkupfile)
	return os.popen(cmd,'r').read()

    def showall(self):
	import time
	files = tarfile.open(self.bkupfile,'r').getmembers()
	for file in files:
	    print '%s \t %s' %(time.strftime('%Y-%m-%d %X',
		time.localtime(file.mtime)), file.name)

    def _runandmodifymsg(self, command, string):
	omsg = os.popen(command,'r').read().split()
	if omsg == []:	return
	nmsg = '\n'.join([msg+string for msg in omsg])
	print nmsg

    def _inarchive(self, file):
	tf = tarfile.open(self.bkupfile,'r')
	return file in tf.getnames()

if __name__=='__main__':
    import sys
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-u','--update',dest='update', \
	    action='store_true', default=False,\
	    help='update all backup files.')
    parser.add_option('-l','--list',dest='list', \
	    action='store_true', default=False,\
	    help='list backup files in the achieve.')
    parser.add_option('-r','--restore',dest='restore',\
	    action='store_true', default=False,\
	    help='restore all backup files. Equivalent to "tar xPvf BACKUP.tar".')
    parser.add_option('-e','--extract',dest='extract',\
	    action='store_true', default=False,\
	    help='extract and restore the specified files.')
    parser.add_option('-d','--delete',dest='delete',\
	    action='store_true', default=False,\
	    help='delete the specified backup files.')
    opts, args = parser.parse_args(sys.argv[1:])
    a = FileBackup(bkupfile=backup_file)
    optc = 0
    for opt in [opts.update, opts.list, \
	    opts.restore, opts.extract, opts.delete]:
	if opt :	    optc += 1
    if optc >=2:    sys.exit('Invalid options.')
    if optc ==1:
	if opts.list:		a.showall()
	if opts.delete:		a.delete(args)
	if opts.update:		a.backup(args)
	if opts.restore:	a.restore()
	if opts.extract:	a.extract(args)
    else:
	a.append(args)
弄个dropbox空间来备份文件或者做私人代码服务器
配置:[url]git://github.com/roylez/dotfiles.git[/url]
主页:http://roylez.heroku.com
各种稀奇玩意儿:http://dooloo.info
maikafei
帖子: 370
注册时间: 2006-03-22 3:42
送出感谢: 0
接收感谢: 0

#2

帖子 maikafei » 2008-04-05 21:29

怎么用? :twisted:
头像
qiang_liu8183
论坛版主
帖子: 10670
注册时间: 2006-09-10 22:36
来自: 北京
送出感谢: 1 次
接收感谢: 6 次

#3

帖子 qiang_liu8183 » 2008-04-05 22:03

maikafei 写了:怎么用? :twisted:
保存为backup.py
终端里运行

代码: 全选

python backup.py
看破、放下、自在、随缘、念佛
真诚、清净、平等、正觉、慈悲
zhuge000
帖子: 101
注册时间: 2008-04-18 17:06
送出感谢: 0
接收感谢: 0

#4

帖子 zhuge000 » 2008-04-30 12:22

大概解释一下呗,看不懂,不敢用……
回复

回到 “Python/Php/Perl”