Python ftp操作脚本&常用函数


需求:快速进行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.   
  6. import sys,os,ftplib,socket  
  7.   
  8. CONST_HOST = "your ftp host or ip"  
  9. CONST_USERNAME = "your username"  
  10. CONST_PWD = "your password"  
  11. CONST_BUFFER_SIZE = 8192  
  12.   
  13. COLOR_NONE = "\033[m"  
  14. COLOR_GREEN = "\033[01;32m"  
  15. COLOR_RED = "\033[01;31m"  
  16. COLOR_YELLOW = "\033[01;33m"  
  17.   
  18. def connect():  
  19.   try:  
  20.     ftp = ftplib.FTP(CONST_HOST)  
  21.     ftp.login(CONST_USERNAME,CONST_PWD)  
  22.     return ftp  
  23.   except socket.error,socket.gaierror:  
  24.     print("FTP is unavailable,please check the host,username and password!")  
  25.     sys.exit(0)  
  26.   
  27. def disconnect(ftp):  
  28.   ftp.quit()  
  29.   
  30. def upload(ftp, filepath):  
  31.   f = open(filepath, "rb")  
  32.   file_name = os.path.split(filepath)[-1]  
  33.   try:  
  34.     ftp.storbinary('STOR %s'%file_name, f, CONST_BUFFER_SIZE)  
  35.   except ftplib.error_perm:  
  36.     return False  
  37.   return True  
  38.   
  39. def download(ftp, filename):  
  40.   f = open(filename,"wb").write  
  41.   try:  
  42.     ftp.retrbinary("RETR %s"%filename, f, CONST_BUFFER_SIZE)  
  43.   except ftplib.error_perm:  
  44.     return False  
  45.   return True  
  46.   
  47. def list(ftp):  
  48.   ftp.dir()  
  49.   
  50. def find(ftp,filename):  
  51.   ftp_f_list = ftp.nlst()  
  52.   if filename in ftp_f_list:  
  53.     return True  
  54.   else:  
  55.     return False  
  56.   
  57. def help():  
  58.   print("help info:")  
  59.   print("[./ftp.py l]\t show the file list of the ftp site ")  
  60.   print("[./ftp.py f filenamA filenameB]\t check if the file is in the ftp site")  
  61.   print("[./ftp.py p filenameA filenameB]\t upload file into ftp site")  
  62.   print("[./ftp.py g filenameA filenameB]\t get file from ftp site")  
  63.   print("[./ftp.py h]\t show help info")  
  64.   print("other params are invalid")  
  65.   
  66.   
  67. def main():  
  68.   args = sys.argv[1:]  
  69.   if len(args) == 0:  
  70.     print("Params needed!")  
  71.     sys.exit(0)  
  72.   
  73.   ftp = connect()  
  74.   
  75.   if args[0] == "p":  
  76.     f_list = args[1:]  
  77.     for up_file in f_list:  
  78.       if not os.path.exists(up_file):  
  79.         print(("UPLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE+"  :file not exist")%up_file)  
  80.         continue  
  81.       elif not os.path.isfile(up_file):  
  82.         print(("UPLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE+"  :%s is not a file")%(up_file,up_file))  
  83.         continue  
  84.   
  85.       if upload(ftp, up_file):  
  86.         print(("UPLOAD: %s "+COLOR_GREEN+"SUCCESS"+COLOR_NONE)%up_file)  
  87.       else:  
  88.         print(("UPLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE)%up_file)  
  89.   elif args[0] == "g":  
  90.     f_list = args[1:]  
  91.     for down_file in f_list:  
  92.       if not find(ftp,down_file):  
  93.         print(("DOWNLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE+"  :%s is not in the ftp site")%(down_file,down_file))  
  94.         continue  
  95.   
  96.       if download(ftp, down_file):  
  97.         print(("DOWNLOAD: %s "+COLOR_GREEN+"SUCCESS"+COLOR_NONE)%down_file)  
  98.       else:  
  99.         print(("DOWNLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE)%down_file)  
  100.   
  101.   elif args[0] == "l":  
  102.     list(ftp)  
  103.   elif args[0] == "f":  
  104.     f_list = args[1:]  
  105.     for f_file in f_list:  
  106.       if find(ftp,f_file):  
  107.         print(("SEARCH: %s "+COLOR_GREEN+"EXIST"+COLOR_NONE)%f_file)  
  108.       else:  
  109.         print(("SEARCH: %s "+COLOR_RED+"NOT EXIST"+COLOR_NONE)%f_file)  
  110.   
  111.   elif args[0] == "h":  
  112.     help()  
  113.   else:  
  114.     print("args are invalid!")  
  115.     help()  
  116.   
  117.   disconnect(ftp)  
  118.   
  119.   
  120.   
  121. if __name__ == "__main__":  
  122.   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) 创建远程目录

相关内容