Python写的数据库备份程序
作者 : admin 于 2009年04月22日, 01:55:00
2009
04-22
04-22
下载地址:mysqlbak
- #!/var/opt/python-2.5/bin/python
- import os
- import time
- import MySQLdb
- CFG = {}
- CFG['root'] = {}
- CFG['root']['hostname'] = 'localhost'
- CFG['root']['username'] = 'root'
- CFG['root']['password'] = 'test'
- CFG['mysqldump'] = '/opt/mysql-5.0.22/bin/mysqldump'
- CFG['time'] = time.strftime("%Y-%m-%d", time.localtime(time.time()) )
- CFG['bakpath'] = '/tmp/' + CFG['time']
- CFG['mainbak'] = '/home/sunboyu/databak/' + CFG['time']
- if os.path.exists( CFG['bakpath'] ) == False:
- os.mkdir( CFG['bakpath'] )
- if os.path.exists( CFG['mainbak'] ) == False:
- os.mkdir( CFG['mainbak'] )
- def mysql_database_bak( database ):
- global CFG
- DIR = CFG['bakpath'] + "/" + database
- if os.path.exists( DIR )==False:
- os.mkdir( DIR )
- conn = MySQLdb.connect( host = CFG['root']['hostname'] , user = CFG['root']['username'] , passwd = CFG['root']['password'] , db = database )
- db = conn.cursor()
- sql = "show tables";
- db.execute( sql )
- result = {}
- for recordline in db.fetchall():
- os.system( CFG['mysqldump'] + " --opt " + database + " " + recordline[0] + " -u" + CFG['root']['username'] + " -p" + CFG['root']['password'] + " > " + DIR + "/" + database + "_" + recordline[0] + ".sql" )
- os.system( "tar cvf " + CFG['bakpath'] + "/" + database + ".tar.gz " + CFG['bakpath'] + "/" + database )
- os.system( "mv " + CFG['bakpath'] + "/" + database + ".tar.gz " + CFG['mainbak'] + '/' )
- conn = MySQLdb.connect( host = CFG['root']['hostname'] , user = CFG['root']['username'] , passwd = CFG['root']['password'] , db = 'test' )
- sql = "show databases";
- db = conn.cursor()
- db.execute( sql )
- result = {}
- bigcount = 0
- for recordline in db.fetchall():
- littlecount = 0
- result[bigcount] = {}
- for colnum in db.description:
- result[bigcount][colnum[0]] = recordline[littlecount]
- littlecount += 1
- bigcount += 1
- for tables in result:
- mysql_database_bak( result[tables]['Database'] )
- os.system( "rm -rf /tmp/" + CFG['time'] ) #警告 rm -rf 这个命令相当危险,使用一定要谨慎