使用到的模組 ftplib
程式碼託管位置 github-pytools
需求
快速進行ftp上傳 ,下載,查詢檔案
原來直接在shell下操作:需要【連線,輸使用者名稱,輸密碼,單檔案操作,存在超時限制】
太過於繁瑣,容易操作失敗
改進
一句命令,搞定多檔案上傳,下載,查詢,列表等操作
後期可以加入更強大的功能
原始碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
#!/usr/bin/python # -*- coding:utf-8 -*- #ftp.py # wklken@yeah.net #this script is used to do some operations more convenient via ftp #1.[p]upload many files in the same time,show md5s #2.[g]download many files in the same time,show md5s #3.[l]list all the files on ftp site #4.[f]search a file on ftp site,return True or Flase #5.[h]show help info #add upload and download operations 20111210 version0.1 #add md5sum after ops 20120308 version0.2 import sys,os,ftplib,socket CONST_HOST = "ip" CONST_USERNAME = "username" CONST_PWD = "pwd" CONST_BUFFER_SIZE = 8192 COLOR_NONE = "33[m" COLOR_GREEN = "33[01;32m" COLOR_RED = "33[01;31m" COLOR_YELLOW = "33[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 are invalid") def main(): args = sys.argv[1:] if len(args) == 0: print("Params needed!") sys.exit(0) ftp = connect() success_list = [] failed_list = [] 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): success_list.append(up_file) else: failed_list.append(up_file) if len(success_list) > 0 : print((COLOR_GREEN + "UPLOAD SUCCESS: %s" + COLOR_NONE)%(" ".join(success_list))) print("md5sum:") for f in success_list: print( os.popen("md5sum " + f).read()[:-1]) if len(failed_list) > 0: print((COLOR_RED + "UPLOAD FAILED: %s" + COLOR_NONE)%(" ".join(failed_list))) 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): success_list.append(down_file) else: failed_list.append(down_file) if len(success_list) > 0 : print((COLOR_GREEN + "DOWNLOAD SUCCESS: %s" + COLOR_NONE)%(" ".join(success_list))) print("md5sum:") for f in success_list: print( os.popen("md5sum " + f).read()[:-1]) if len(failed_list) > 0: print((COLOR_RED + "DOWNLOAD FAILED: %s" + COLOR_NONE)%(" ".join(failed_list))) 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) if len(f_file) > 3: print("Similar File List:") s = ftp.nlst() print ", ".join([k for k in s if f_file in k]) elif args[0] == "h": help() else: print("args are invalid!") help() disconnect(ftp) if __name__ == "__main__": main() |
常用函式
用手冊檢視,以下只是簡略,因為沒用用到,[待整理]:
1 2 3 4 5 6 7 8 9 10 11 12 |
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) 建立遠端目錄 |
打賞支援我寫出更多好文章,謝謝!
打賞作者
打賞支援我寫出更多好文章,謝謝!
任選一種支付方式