最近,正好发生了一件大事,就是 GitLab 的运维同学不小心删除了生产的数据,虽然 GitLab 已经骇人听闻的准备了五种备份机制,但是,仍然导致他们丢失了将近 6 个小时的用户数据,尤其对他们声誉的损失,是根本无法估量的。反思一下,这个博客 Becomin' Charles,也是没有完善的备份的,真是冷汗直冒啊,主要考虑到这是我的个人博客,但是想想已经坚持了快十年了,如果真的丢了的话,还是非常痛心的。
正好,老婆最近正在学习Python 编程,我在教她,其实,我是PHP 程序员,一点也不喜欢 Python,但是说实在,一个外行学编程的话,Python 确实比PHP 友好太多了,只能推荐她学 Python 了。正好,借着这个机会,我决定自己也学学 Python 编程吧,于是,我决定要用 Python 做一个数据库的自动备份脚本。备份的位置,就用Dropbox 来做吧,因为我的服务器是 Linode 提供的,美国 fremont 机房,选择美国的存储服务,比较合适。以下是我写得代码,Python 小白,敬请指教:
#!/usr/bin/python#coding:utf-8 import sysimport osfrom yamlimport loadfrom datetime import datetimeimport dropboxfrom dropbox.filesimport WriteModefrom dropbox.exceptions import ApiError, AuthError if len(sys.argv) < 2: print >>sys.stderr, "Usage: %s <config_file>" % sys.argv[0] sys.exit(0) conf = load(file(sys.argv[1], 'r')) # config file is a YAML looks like# ---# server-name: 127.0.0.1# local-backup-path: /tmp# remote-backup-path: /backup# dropbox-token: jdkgjdkjg# databases:# - host: localhost# port: 3306# user: user# pass: password# name: database1# charset: utf8# - host: localhost# port: 3306# user: user2# pass: password2# name: database2# charset: utf8 for dbin conf['databases'] : filename = "%s_%s.sql" % (db['name'], datetime.now().strftime("%Y%m%d-%H-%M-%S")) filepath = "%s/%s" % (conf['local-backup-path'], filename) cmd = "mysqldump -h%s -u%s -p%s -P%s --single-transaction %s > %s" % ( db['host'], db['user'], db['pass'], db['port'], db['name'], filepath ) os.system(cmd) cmd = "gzip %s" % filepath os.system(cmd) filepath = filepath + '.gz' dbx = dropbox.Dropbox(conf['dropbox-token']) backuppath = "%s/%s/%s/%s" % ( conf['remote-backup-path'], # remote path datetime.now().strftime("%Y%m%d"), # date string conf['server-name'], # server name filename + '.gz') with open(filepath, 'rb') as f: time = datetime.now().strftime("%Y-%m-%d %H:%M:%S ") print(time + "Uploading " + filepath + " to Dropbox as " + backuppath) try: dbx.files_upload(f.read(), backuppath, mode=WriteMode('overwrite')) except ApiErroras err: # This checks for the specific error where a user doesn't have # enough Dropbox space quota to upload this file if (err.error.is_path() and err.error.get_path().error.is_insufficient_space()): sys.exit("ERROR: Cannot back up; insufficient space.") elif err.user_message_text: print(err.user_message_text) sys.exit() else: print(err) sys.exit()
新闻热点
疑难解答