Ftp upload log of python script
Because the ssoc logs are huge, they quickly fill up the disk. Need to upload the backup to the ftp server every day, so according to the information on the Internet, I made a simple script. It's the first time I've cobbled together a script. It's also simple, especially the simplification of exception handling. Because of its singleness, the screen output is then written directly to the local file with the pipe command, which acts as a log. It's a lazy version. It needs to be processed.
1 ftp upload the contents of the folder
Delete the files in the existing directory after uploading.
The advantage of simplification is to simply traverse the file and upload it if there is a new file.
The code is as follows:
Import ftplib
Import os
Import shutil
Import time
Def ftpconnect ():
Ftp_server = 'x.x.x.x' # FTP server ip address
Username = 'xxxx'
Password = 'xxxx'
Timeout = 30
Port = 21
Ftp = ftplib.FTP () ftp.set_debuglevel (2) # open debuglevel 2, can display detail messageftp.connect (ftp_server, port, timeout) # connect to FTP serverftp.login (username, password) return ftp
Def uploadfile_to_FTP ():
Ftp = ftpconnect ()
Print ftp.getwelcome () # can display FTP server welcome message.
Bufsize = 1024for filename in os.listdir (r "/ data/data/event"): remotepath = "/ safe-logs/" + filename localpath = "/ data/data/event/" + filename fp = open (localpath, 'rb') ftp.storbinary (' STOR'+ remotepath, fp, bufsize) # start to upload file: local-- > FTP serverftp.set_debuglevel (0) # close debugfp.close () # close connectftp.quit () # quit FTP server
Def cleanfile ():
Shutil.rmtree ("/ data/data/event")
Os.mkdir ("/ data/data/event")
Def print_time ():
Localtime=time.asctime (time.localtime (time.time ()
Print'\ n'
Print "localtime:", localtime
If name = = "main":
Downloadfile_from_FTP () print_time () uploadfile_to_FTP () cleanfile ()