歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python ftp操作腳本&常用函數

Python ftp操作腳本&常用函數

日期:2017/3/1 10:49:03   编辑:Linux編程

需求:快速進行ftp上傳 ,下載,查詢文件

原來直接在shell下操作:

需要【連接,輸用戶名,輸密碼,單文件操作,存在超時限制】

太過於繁瑣,容易操作失敗

腳本改進:

一句命令,搞定多文件上傳,下載,查詢,列表等操作

後期可以加入更強大的功能

直接上腳本:

  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 are 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 are invalid!")
  97. help()
  98. disconnect(ftp)
  99. if __name__ == "__main__":
  100. main()

常用函數:

用手冊查看,以下只是簡略,因為沒用用到,[待整理]:

login(user='',passwd='', acct='') 登錄到FTP 服務器,所有的參數都是可選的
pwd() 當前工作目錄
cwd(path) 把當前工作目錄設置為path
dir([path[,...[,cb]]) 顯示path 目錄裡的內容,可選的參數cb 是一個回調函數,會被傳給retrlines()方法
nlst([path[,...]) 與dir()類似,但返回一個文件名的列表,而不是顯示這些文件名
retrlines(cmd [, cb]) 給定FTP 命令(如“RETR filename”),用於下載文本文件。可選的回調函數cb 用於處理文件的每一行
retrbinary(cmd, cb[,bs=8192[, ra]]) 與retrlines()類似,只是這個指令處理二進制文件。回調函數cb 用於處理每一塊(塊大小默認為8K)下載的數據。
storlines(cmd, f) 給定FTP 命令(如“STOR filename”),以上傳文本文件。要給定一個文件對象f
storbinary(cmd, f[,bs=8192]) 與storlines()類似,只是這個指令處理二進制文件。要給定一個文件對象f,上傳塊大小bs 默認為8Kbs=8192])
rename(old, new) 把遠程文件old 改名為new
delete(path) 刪除位於path 的遠程文件
mkd(directory) 創建遠程目錄

Copyright © Linux教程網 All Rights Reserved