Requirements: Fast ftp upload, download, query files
Originally operated directly under the shell:
Need to "Connect, lose user name, lose password, single file operation, there is a timeout limit"
Too cumbersome, easy to operate failed
Scripting improvements:
A command, take care of multi-file upload, download, query, list and other operations
Later, you can add more powerful features
Directly on the script:
- #!/usr/bin/python
- #ftp. py
- #this script is used to make some FTP operations more convenient
- #add upload and download operations 20111210 version0.1
- Import Sys,os,ftplib,socket
- Const_host = "Your ftp HOST or IP"
- Const_username = "Your USERNAME"
- Const_pwd = "Your password"
- Const_buffer_size = 8192
- Color_none = "\033[m"
- Color_green = "\033[01;32m"
- color_red = "\033[01;31m"
- Color_yellow = "\033[01;33m"
- Def connect ():
- Try:
- FTP = Ftplib. FTP (Const_host)
- Ftp.login (CONST_USERNAME,CONST_PWD)
- return FTP
- except Socket.error,socket.gaierror:
- print ("FTP is unavailable,please check the host,username and password!")
- Sys.exit (0)
- def disconnect (FTP):
- Ftp.quit ()
- def upload (FTP, filepath):
- f = open (filepath, "RB")
- file_name = Os.path.split (filepath) [-1]
- Try:
- Ftp.storbinary (' STOR%s '%file_name, F, const_buffer_size)
- except Ftplib.error_perm:
- return False
- return True
- def download (FTP, filename):
- f = open (filename,"WB"). Write
- Try:
- Ftp.retrbinary ("RETR%s"%filename, F, const_buffer_size)
- except Ftplib.error_perm:
- return False
- return True
- def list (FTP):
- Ftp.dir ()
- def find (Ftp,filename):
- Ftp_f_list = Ftp.nlst ()
- if filename in ftp_f_list:
- return True
- Else:
- return False
- def help ():
- print ("Help info:")
- Print ("[./ftp.py l]\t Show the file list of the FTP site")
- Print ("[./ftp.py f Filenama filenameb]\t Check if the file is in the FTP site")
- Print ("[./ftp.py p Filenamea filenameb]\t upload file into FTP site")
- Print ("[./ftp.py g Filenamea filenameb]\t get file from FTP site")
- Print ("[./ftp.py h]\t Show Help Info")
- Print ("Other params is invalid")
- def main ():
- args = sys.argv[1:]
- if Len (args) = = 0:
- print ("Params needed!")
- Sys.exit (0)
- FTP = Connect ()
- if args[0] = = "P":
- F_list = args[1:]
- For Up_file in f_list:
- If not os.path.exists (up_file):
- print ("UPLOAD:%s" +color_red+"FAILED" +color_none+": File not Exist")%up_file)
- Continue
- elif not os.path.isfile (up_file):
- print ("UPLOAD:%s" +color_red+"FAILED" +color_none+":%s is not a file")% (up_file,up_file))
- Continue
- if Upload (FTP, up_file):
- Print (("UPLOAD:%s" +color_green+"SUCCESS" +color_none)%up_file)
- Else:
- Print (("UPLOAD:%s" +color_red+"FAILED" +color_none)%up_file)
- elif args[0] = = "G":
- F_list = args[1:]
- For Down_file in f_list:
- If not find (ftp,down_file):
- print ("DOWNLOAD:%s" +color_red+"FAILED" +color_none+":%s is not in the FTP site")% (Down_file,down_ file))
- Continue
- if Download (FTP, down_file):
- Print (("DOWNLOAD:%s" +color_green+"SUCCESS" +color_none)%down_file)
- Else:
- Print (("DOWNLOAD:%s" +color_red+"FAILED" +color_none)%down_file)
- elif args[0] = = "L":
- List (FTP)
- elif args[0] = = "F":
- F_list = args[1:]
- For F_file in f_list:
- if Find (ftp,f_file):
- Print (("SEARCH:%s" +color_green+"EXIST" +color_none)%f_file)
- Else:
- print ("SEARCH:%s" +color_red+"not EXIST" +color_none)%f_file)
- elif args[0] = = "h":
- Help ()
- Else:
- print ("args is invalid!")
- Help ()
- Disconnect (FTP)
- if __name__ = = "__main__":
- Main ()
Common functions:
In the manual view, the following is only brief, because useless, [to be sorted]:
Login (user= ', passwd= ', acct= ') to the FTP server, all parameters are optional
PWD () Current working directory
CWD (path) sets the current working directory to Path
Dir ([path[,... [, CB]]) Displays the contents of the path directory, the optional parameter CB is a callback function that is passed to the Retrlines () method
Nlst ([path[,...]) is similar to Dir (), but returns a list of file names instead of displaying them
Retrlines (cmd [, CB]) given an FTP command (such as "RETR filename") for downloading a text file. Optional callback function CB is used to process each line of the file
Retrbinary (cmd, cb[,bs=8192[, RA]) is similar to Retrlines (), except that this instruction handles binary files. The callback function CB is used to process each piece of data downloaded (The block size defaults to 8K).
Storlines (cmd, f) is given an FTP command (such as "STOR filename") to upload a text file. To be given a file object F
Storbinary (cmd, f[,bs=8192]) is similar to Storlines (), except that this instruction handles binary files. To give a file object F, the upload block size BS defaults to 8kbs=8192])
Rename (old, new) rename the remote file old to new
Delete (path) deletes the remote file located in path
MKD (directory) to create a remote directory
Python FTP action Scripts & common functions