Guest User

Untitled

a guest
Oct 21st, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.07 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3.  
  4. # This file is backup script of MySQL in SAKURA's rental server.
  5. #
  6. # Backup is using the mysqldump command.
  7. # Dump file is stored in directory specified.
  8. # Dump files that are older than for the specified period will be removed.
  9. # Can be run from the command line or cron.
  10. #
  11. # Remote backup is using sftp.
  12. # If exists SSH private key, key is used for authentication
  13. # Can be remote backup, by specify a remote server in argument.
  14. # Example) backupDatabase.py [USER@]SERVER[:PORT] [PASSWORD]
  15. # * If you not specify user, use login user .
  16. # * If you not specify port, use port 22.
  17. #
  18. # This script is required MySQLdb module.
  19. # * If you want remote backup, required ssh module.
  20.  
  21. import os
  22. import sys
  23. import time
  24. import datetime
  25. import getpass
  26. import glob
  27. from subprocess import call
  28. # External module
  29. import MySQLdb
  30.  
  31. # Database connection infomation
  32. HOST = 'mysqlXXX.db.sakura.ne.jp'
  33. USER = getpass.getuser()
  34. PASSWD = '******'
  35.  
  36. # Backup directory and backup command
  37. BKDIR = os.path.expanduser('~/backup/mysql')
  38. DTIME = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
  39. TMPLT = '/usr/local/bin/mysqldump -c -Q -h{0} -p{1} {2} > {3}/{2}_{4}.sql'
  40.  
  41. # Retention period
  42. DEL_DAY = 90
  43.  
  44. # Remote backup settings
  45. remote_backup = False
  46. if len(sys.argv) > 1:
  47. try:
  48. # External module
  49. import ssh
  50. rhost = sys.argv[1]
  51. ruser = getpass.getuser()
  52. rport = 22
  53. priv_key = os.path.expanduser('~/.ssh/id_rsa')
  54. # Remote backup directory
  55. RBKDIR = '/usr/local/backup'
  56. if rhost.find('@') >= 0:
  57. ruser, rhost = rhost.split('@')
  58.  
  59. if rhost.find(':') >= 0:
  60. rhost, rport = rhost.split(':')
  61. rport = int(rport)
  62.  
  63. # RSA Key passphrase or remote server password
  64. RPASS = '******'
  65. if len(sys.argv) > 2:
  66. RPASS = sys.argv[2]
  67. t = ssh.Transport((rhost, rport))
  68. if os.path.isfile(priv_key):
  69. key = ssh.RSAKey.from_private_key_file(priv_key, RPASS)
  70. t.connect(username=ruser, pkey=key)
  71. else:
  72. t.connect(username=ruser, password=RPASS)
  73. sftp = ssh.SFTPClient.from_transport(t)
  74. remote_backup = True
  75. except Exception as e:
  76. print(e)
  77.  
  78. # Get database list
  79. conn = MySQLdb.connect(host=HOST, port=3306, user=USER, passwd=PASSWD)
  80. cur = conn.cursor(MySQLdb.cursors.DictCursor)
  81. cur.execute("SET NAMES utf8")
  82. sql = "SHOW DATABASES LIKE '{0}%'".format(USER)
  83. cur.execute(sql)
  84. res = cur.fetchall()
  85. dbs = [ d.values()[0] for d in res ]
  86. cur.close()
  87. conn.close()
  88.  
  89. # Database backup and remote backup
  90. cmds = [ TMPLT.format(HOST, PASSWD, db, BKDIR, DTIME) for db in dbs ]
  91. for cmd in cmds:
  92. file = cmd.split()[-1]
  93. retcode = call(cmd, shell=True)
  94. if remote_backup:
  95. sftp.put(file, os.path.join(RBKDIR, os.path.basename(file)))
  96.  
  97. # Delete
  98. dtime = datetime.date.today() - datetime.timedelta(days=90)
  99. epoc = time.mktime(dtime.timetuple())
  100. files = { f: os.path.getctime(f) for f in glob.iglob(os.path.join(BKDIR, '*')) }
  101. for file in files:
  102. if epoc > files[file]:
  103. os.unlink(file)
  104.  
  105. if remote_backup:
  106. t.close()
Add Comment
Please, Sign In to add comment