Warning: curl_exec() has been disabled for security reasons in /pub/host/sunboyu/sunboyu/www/wp-includes/http.php on line 1022
Python写的数据库备份程序 » Blog Archive 一个程序猿 孙小一,孙小二,PHP,MYSQL,LINUX,APACHE,原创技术,扯淡

Python写的数据库备份程序

作者 : admin 于 2009-04-22 01:55:00 标签: ,
2009
04-22

下载地址:mysqlbak

  1. #!/var/opt/python-2.5/bin/python
  2. import os
  3. import time
  4. import MySQLdb
  5.  
  6.  
  7. CFG = {}
  8. CFG['root'] = {}
  9. CFG['root']['hostname'] = 'localhost'
  10. CFG['root']['username'] = 'root'
  11. CFG['root']['password'] = 'test'
  12.  
  13.  
  14. CFG['mysqldump'] = '/opt/mysql-5.0.22/bin/mysqldump'
  15.  
  16. CFG['time'] = time.strftime("%Y-%m-%d", time.localtime(time.time()) )
  17.  
  18. CFG['bakpath'] = '/tmp/' + CFG['time']
  19. CFG['mainbak'] = '/home/sunboyu/databak/' + CFG['time']
  20.  
  21.  
  22. if os.path.exists( CFG['bakpath'] ) == False:
  23.     os.mkdir( CFG['bakpath'] )
  24. if os.path.exists( CFG['mainbak'] ) == False:
  25.     os.mkdir( CFG['mainbak'] )
  26.  
  27. def mysql_database_bak( database ):
  28.     global CFG
  29.     DIR = CFG['bakpath'] + "/" + database
  30.     if os.path.exists( DIR )==False:
  31.         os.mkdir( DIR )
  32.     conn = MySQLdb.connect( host = CFG['root']['hostname'] , user = CFG['root']['username'] , passwd = CFG['root']['password'] , db = database )
  33.     db = conn.cursor()
  34.     sql = "show tables";
  35.     db.execute( sql )
  36.     result = {}
  37.     for recordline in db.fetchall():
  38.         os.system( CFG['mysqldump'] + " --opt  " + database + " " + recordline[0] + " -u" + CFG['root']['username'] + " -p" + CFG['root']['password'] + " > " + DIR + "/" + database + "_" + recordline[0] + ".sql" )
  39.     os.system( "tar cvf " + CFG['bakpath'] + "/" + database + ".tar.gz " +  CFG['bakpath'] + "/" + database )
  40.     os.system( "mv " + CFG['bakpath'] + "/" + database + ".tar.gz " + CFG['mainbak'] + '/' )
  41.  
  42.  
  43. conn = MySQLdb.connect( host = CFG['root']['hostname'] , user = CFG['root']['username'] , passwd = CFG['root']['password'] , db = 'test' )
  44. sql = "show databases";
  45. db = conn.cursor()
  46. db.execute( sql )
  47. result = {}
  48. bigcount = 0
  49. for recordline in db.fetchall():
  50. littlecount = 0
  51. result[bigcount] = {}
  52. for colnum in db.description:
  53.     result[bigcount][colnum[0]] = recordline[littlecount]
  54.     littlecount += 1
  55. bigcount += 1
  56.  
  57.  
  58. for tables in result:
  59.     mysql_database_bak( result[tables]['Database'] )
  60.  
  61. os.system( "rm -rf /tmp/" + CFG['time'] )  #警告 rm -rf 这个命令相当危险,使用一定要谨慎

评论 3

  1. admin Says:

    貌似ftp到远程的存储介质上会更安全

  2. antidote Says:

    一个一个表的去备份…?

  3. admin Says:

    分开备份,当你要恢复一个表的时候比较方便

发表评论




XHTML:你可以使用的标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(若看不到验证码,请重新加载页面。)