【準備工做】html
搭建 FTP 服務器:Windows Server 2008 R2 搭建FTP服務python
若是本機訪問報 530 錯誤:一、檢查用戶名、密碼;二、檢查 ftp 目錄的用戶權限。mysql
若是遠程主機沒法訪問,檢查防火牆。sql
關於 ftp 的端口:控制端口爲21;數據端口在主動模式(PORT)下爲20,被動模式(PASV)下不定。數據庫
開啓被動模式:在「FTP 防火牆支持」裏面配置端口,而後重啓「Microsoft FTP Service」服務。注意具體 ftp 站點的數據框是灰色的,須要在 IIS 總站點配置。服務器
【code】
app
如下代碼對 Windows 下 MariaDB 10.1.18,Ubuntu 下 MySQL 5.7.23 測試可行。ide
# encoding: utf-8 # author: walker # date: 2018-08-02 # summary: Python3 備份 MySQL/MariaDB(本地+FTP),一個庫一個文件 import os import time import pymysql import pprint import psutil from ftplib import FTP DBHost = r'127.0.0.1' DBPort = 3306 DBUser = r'root' DBPwd = r'password' # LocalBakRoot = r'/home/walker/sql_bak' # 本地備份目錄 LocalBakRoot = r'D:\sql_bak' # 本地備份目錄 LocalIP = '' FtpHost = r'192.168.xx.xx' # FTP 主機 FtpBakRoot = r'sql_bak' # FTP 目錄 FtpUser = r'ftpadmin' FtpPwd = r'password' # 忽略掉系統庫 IgnoreDB = {'information_schema', 'mysql', 'performance_schema', 'sys'} # 根據前綴獲取IP def GetLocalIPByPrefix(prefix): localIP = '' dic = psutil.net_if_addrs() for adapter in dic: snicList = dic[adapter] for snic in snicList: if not snic.family.name.startswith('AF_INET'): continue ip = snic.address if ip.startswith(prefix): localIP = ip return localIP # 處理一個數據庫 def ProcOneDB(dbName): print('ProcOneDB %s ...' % dbName) filename = '%s_%s_%s.sql' % (time.strftime('%Y%m%d', time.localtime()), LocalIP, dbName) localFile = os.path.join(LocalBakRoot, filename) #備份數據庫,若是沒有 -B 參數不會導出數據庫建立語句 cmd = 'mysqldump -u%s -p%s -B %s > %s' % (DBUser, DBPwd, dbName, localFile) # print('cmd: %s' % cmd) print('mysqldump ...') rtn = os.system(cmd) if 0 != rtn: print('Error: 0 != rtn') return False ftp = FTP() ftp.encoding = 'gb18030' ftp.set_pasv(False) ftp.connect(FtpHost, port=21, timeout=10) ftp.login(user=FtpUser, passwd=FtpPwd) print(ftp.getwelcome()) ftp.cwd(FtpBakRoot) # 以 sql 服務器 ip 做爲子目錄名 if LocalIP not in ftp.nlst(): ftp.mkd(LocalIP) # 建立子目錄 ftp.cwd(LocalIP) with open(localFile, mode='rb') as f: ftp.storbinary('STOR ' + filename, f) return True # 處理全部數據庫 def ProcAllDB(): connDB = pymysql.connect(host=DBHost, port=DBPort, user=DBUser, passwd=DBPwd, charset='utf8mb4') cur = connDB.cursor() sql = "show databases;" print('input sql:' + sql) cur.execute(sql) rowList = cur.fetchall() cur.close() connDB.close() dbList = list() for row in rowList: dbList.append(row[0]) print('dbList(%d):\n%s\n' % (len(dbList), pprint.pformat(dbList, indent=4))) for dbName in dbList: if dbName in IgnoreDB: continue print('current time: %s' % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) ProcOneDB(dbName) print('current time: %s\n' % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) if __name__ == '__main__': LocalIP = GetLocalIPByPrefix('192.168.xx.') ProcAllDB()
【相關閱讀】測試
FTP 目錄同步:pyftpsync
*** walker ***