CopyCode The Code is as follows :#! /Usr/bin/Python
Import OS
Import time
Import ftplib
Import traceback
# Config vars
Systempathchr = "/" # path delimiter, * nix "/" Win32 "\\"
Dbuser = "root" # database username
Dbpwd = "dbpwd" # Database Password
Dbnamelist = ["dbone", "dbtwo", "dbthree"] # databases to be backed up
Workdir = "/path/to/backup/" # local backup folder
Errlogfile = "databack. log" # Error Log name
Ftp_addr = "192.168.0.2" # ftp address
Ftp_port = "2102" # ftp port
Ftp_user = "databack" # ftp user name
Ftp_pwd = "backpwd" # ftp Password
Ftp_path = "/" # store it in the FTP path
Ftpqueue = []
Def ftpstor ():
# Login
Bufsize = 1024
FTP = ftplib. FTP ()
Try:
FTP. Connect (ftp_addr, ftp_port)
FTP. login (ftp_user, ftp_pwd)
FTP. CWD (ftp_path)
For filepath in ftpqueue:
# Open File for input as binary
F = open (filepath, "rb ")
# Store file as binary
Print getfilename (filepath)
FTP. storbinary ("stor" + getfilename (filepath), F, bufsize)
F. Close ()
FTP. Quit ()
Except t:
Path = OS. Path. Join (workdir, errlogfile)
Traceback. print_exc (file = open (path, ""))
Def dumpdb (dbname ):
Global ftpqueue
Timeformat = "% Y % m % d"
Sqlvalformat = "mysqldump-U % s-p \" % s \ "\" % s \ "> \" % s \""
Tarvalformat = "tar -- directory = \" % s \ "-zcf \" % s \ "\" % s \""
Nowdate = time. strftime (timeformat)
Dumpfile = OS. Path. Join (workdir, dbname + ". Dump ")
Zipfile = OS. Path. Join (workdir, dbname + nowdate + ".tar.gz ")
Sqlval = sqlvalformat % (dbuser, dbpwd, dbname, dumpfile)
Result = OS. System (sqlval)
Tarval = tarvalformat % (workdir, zipfile, dbname + ". Dump ")
Result = OS. System (tarval)
OS. Remove (dumpfile)
Ftpqueue. append (zipfile)
Def getfilename (PATH ):
PT = path. rfind (systempathchr)
Return Path [Pt + 1:]
Def main ():
For dbname in dbnamelist:
Dumpdb (dbname)
Ftpstor ()
Main ()
I did not take a closer look, but we recommend that you look at the OS in the following two sentences. the functions in the path module may not need to set different separators for Linux and Windows respectively.
# config vars
systempathchr = "/" # path delimiter, * nix uses "/" Win32 with "\"
if you see that the code is used to get the file name, try OS. path. basename live OS. path. copy Code the code is as follows: >>> import OS. path
>> OS. path. basename ("C: \ test \ aa.txt")
'aa.txt '
OS. path. split ("C :\\ test \ aa.txt")
('C: \ test', 'aa.txt ')
>>> OS. path. split ("C: \ test \ aa.txt") [-1]
'aa.txt '
OS. path. basename ("/home/test/aa.txt")
'aa.txt '
OS. path. split ("/home/test/aa.txt")
('/home/test', 'aa.txt')
>> OS. path. basename ("/home/test/aa.txt")
'aa.txt '