Python FTP action Scripts & common functions

Source: Internet
Author: User
Tags ftp site

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:

  1. #!/usr/bin/python
  2. #ftp. py
  3. #this script is used to make some FTP operations more convenient
  4. #add upload and download operations 20111210 version0.1
  5. Import Sys,os,ftplib,socket
  6. Const_host = "Your ftp HOST or IP"
  7. Const_username = "Your USERNAME"
  8. Const_pwd = "Your password"
  9. Const_buffer_size = 8192
  10. Color_none = "\033[m"
  11. Color_green = "\033[01;32m"
  12. color_red = "\033[01;31m"
  13. Color_yellow = "\033[01;33m"
  14. Def connect ():
  15. Try:
  16. FTP = Ftplib. FTP (Const_host)
  17. Ftp.login (CONST_USERNAME,CONST_PWD)
  18. return FTP
  19. except Socket.error,socket.gaierror:
  20. print ("FTP is unavailable,please check the host,username and password!")
  21. Sys.exit (0)
  22. def disconnect (FTP):
  23. Ftp.quit ()
  24. def upload (FTP, filepath):
  25. f = open (filepath, "RB")
  26. file_name = Os.path.split (filepath) [-1]
  27. Try:
  28. Ftp.storbinary (' STOR%s '%file_name, F, const_buffer_size)
  29. except Ftplib.error_perm:
  30. return False
  31. return True
  32. def download (FTP, filename):
  33. f = open (filename,"WB"). Write
  34. Try:
  35. Ftp.retrbinary ("RETR%s"%filename, F, const_buffer_size)
  36. except Ftplib.error_perm:
  37. return False
  38. return True
  39. def list (FTP):
  40. Ftp.dir ()
  41. def find (Ftp,filename):
  42. Ftp_f_list = Ftp.nlst ()
  43. if filename in ftp_f_list:
  44. return True
  45. Else:
  46. return False
  47. def help ():
  48. print ("Help info:")
  49. Print ("[./ftp.py l]\t Show the file list of the FTP site")
  50. Print ("[./ftp.py f Filenama filenameb]\t Check if the file is in the FTP site")
  51. Print ("[./ftp.py p Filenamea filenameb]\t upload file into FTP site")
  52. Print ("[./ftp.py g Filenamea filenameb]\t get file from FTP site")
  53. Print ("[./ftp.py h]\t Show Help Info")
  54. Print ("Other params is invalid")
  55. def main ():
  56. args = sys.argv[1:]
  57. if Len (args) = = 0:
  58. print ("Params needed!")
  59. Sys.exit (0)
  60. FTP = Connect ()
  61. if args[0] = = "P":
  62. F_list = args[1:]
  63. For Up_file in f_list:
  64. If not os.path.exists (up_file):
  65. print ("UPLOAD:%s" +color_red+"FAILED" +color_none+": File not Exist")%up_file)
  66. Continue
  67. elif not os.path.isfile (up_file):
  68. print ("UPLOAD:%s" +color_red+"FAILED" +color_none+":%s is not a file")% (up_file,up_file))
  69. Continue
  70. if Upload (FTP, up_file):
  71. Print (("UPLOAD:%s" +color_green+"SUCCESS" +color_none)%up_file)
  72. Else:
  73. Print (("UPLOAD:%s" +color_red+"FAILED" +color_none)%up_file)
  74. elif args[0] = = "G":
  75. F_list = args[1:]
  76. For Down_file in f_list:
  77. If not find (ftp,down_file):
  78. print ("DOWNLOAD:%s" +color_red+"FAILED" +color_none+":%s is not in the FTP site")% (Down_file,down_ file))
  79. Continue
  80. if Download (FTP, down_file):
  81. Print (("DOWNLOAD:%s" +color_green+"SUCCESS" +color_none)%down_file)
  82. Else:
  83. Print (("DOWNLOAD:%s" +color_red+"FAILED" +color_none)%down_file)
  84. elif args[0] = = "L":
  85. List (FTP)
  86. elif args[0] = = "F":
  87. F_list = args[1:]
  88. For F_file in f_list:
  89. if Find (ftp,f_file):
  90. Print (("SEARCH:%s" +color_green+"EXIST" +color_none)%f_file)
  91. Else:
  92. print ("SEARCH:%s" +color_red+"not EXIST" +color_none)%f_file)
  93. elif args[0] = = "h":
  94. Help ()
  95. Else:
  96. print ("args is invalid!")
  97. Help ()
  98. Disconnect (FTP)
  99. if __name__ = = "__main__":
  100. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.