最近,正好發生了一件大事,就是 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()
新聞熱點
疑難解答