Python 编写 FTP Client
来源:互联网 发布:成都金域名人酒店小姐 编辑:程序博客网 时间:2024/05/21 09:04
************V 0.4Beta版本************
1.修正了History功能,使得能够正确读写文件,返回正确的值
2.经过一些测试修正了一些微小容易引起崩溃的bug
3.小幅度精简了程序
#!/usr/bin/python'''Created on 2011-11-5@author: zavierxuThis software is a simple FTP client, you can use it to login to your FTP server,download , upload your files. '''from ftplib import FTPimport sys, os,os.path,operatordef download(handle,filename): df = open(filename,"wb") try: handle.retrbinary("RETR " + filename,df.write) except Exception: print "Error in downloading the remote file." return else: print "Successful download!" df.close() returndef upload(handle,filename): uf = open(filename,"rb") (base,ext) = os.path.splitext(filename) try: handle.storbinary("STOR " + filename,uf) except Exception: print "Successful upload." else: print "Successful upload." uf.close() returnprint "This is a simple FTP Slient. You can use it to upload and download"f=file('history.txt','a')f.close()showhis=raw_input ("Would you like to see the history you logged in? yes/no :")if showhis == 'yes': fhis = file('history.txt') num = 0 for linehis in fhis: num += 1 print (str(num) + '.' + linehis) if num == 0: print "There is no login history." f.close()host_name= raw_input ("Please enter the hostname.(For Example: public.sjtu.edu.cn)\nFTP address:")fin=file('history.txt')i=0while 1: linein=fin.readline() if len(linein) == 0: break if host_name == linein: i=1; breakif i == 0: fout=file('history.txt','a') fout.write(host_name) fout.close()host_name = host_name.replace("\n","")user = raw_input("Enter username: ")pwd = raw_input("Enter password: ")try: ftph = FTP(host_name)except: print "Host could not be resolved." raw_input() sys.exit()else: passtry: ftph.login(user,pwd)except Exception: if user == "anonymous" or user == "Anonymous" and pwd == "anonymous" or pwd == "Anonymous": print "The server does not accept anonymous requests." raw_input() sys.exit() else: print "Invalid login combination." raw_input() sys.exit()else: print "Successfully connected!\n"print ftph.getwelcome()path = ftph.pwd()charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"print "Press help at any time to see proper usage.\n"while 1: command = raw_input("FTP ]> ") if "get " in command: rf = command.replace("get ","") rf = rf.replace("\n","") download(ftph,rf) continue elif "put " in command: lf = command.replace("put ","") lf = lf.replace("\n","") upload(ftph,lf) ftph.close() ftph = FTP(host_name) ftph.login(user,pwd) continue elif "mkdir " in command: mkdirname = command.replace("mkdir ","") mkdirname = mkdirname.replace("\n","") try: ftph.mkd(mkdirname) except: print "Incorrect usage." continue else: print "Directory created." continue elif "rmdir " in command: rmdirname = command.replace("rmdir ","") rmdirname = rmdirname.replace("\n","") current = ftph.pwd() ftph.cwd(rmdirname) allfiles = ftph.nlst() for file in allfiles: try: ftph.delete(file) except Exception: pass else: pass ftph.cwd(current) try: ftph.rmd(rmdirname) except Exception: print "All files within the directory have been deleted, but there is still another directory inside. As deleting this directory automatically goes against true FTP protocol, you must manually delete it, before you can delete the entire directory." else: print "Directory deleted." continue elif command == "pwd": print ftph.pwd() continue elif command == "ls": print ftph.dir() continue elif "cd " in command: dirpath = command.replace("cd ","") dirpath = dirpath.replace("\n","") try: ftph.cwd(dirpath) if dirpath=='..': print "Directory changed to " + ftph.pwd() elif dirpath=='.': print "Directory will not change." else: print "Directory changed to " + dirpath except: print "No such directory." continue elif command == "up": dir = ftph.pwd() temp = dir index = len(dir) - 1 for i in range(index,0,-1): if temp[i] == "/" and i != len(dir): ftph.cwd(temp) print "One directory back." continue if(operator.contains(charset,dir[i])): temp = temp[:-1] if temp=="/": ftph.cwd(temp) print "One directory back." elif command == "rename": fromname = raw_input("Current file name: ") toname = raw_input("To be changed to: ") ftph.rename(fromname,toname) print "Successfully renamed." continue elif "rm " in command: delfile = command.replace("rm ","") delfile = delfile.replace("\n","") ftph.delete(delfile) print "File successfully deleted." continue elif "size " in command: szfile = command.replace("size ","") szfile = szfile.replace("\n","") print "The file is " + str(ftph.size(szfile)) + " bytes." continue elif command == "quit": ftph.close() print "Session ended." break elif command == "history": fhis = file('history.txt') num = 0 for linehis in fhis: num += 1 print (str(num) + '.' + linehis) continue elif command == "help": print "size [filename] - returns the size in bytes of the specified file" print "quit - terminate the ftp session" print "rm [filename] - delete a file" print "rename - rename a file" print "up - navigate 1 directory up" print "cd [path] - change which directory you're in" print "pwd - prints the path of the directory you are currently in" print "ls - lists the contents of the directory" print "rmdir [directory path] - removes/deletes an entire directory" print "mkdir [directory path] - creates a new directory" print "put [filename] - stores a local file onto the server (does not work with microsoft office document types)" print "get [filename] - download a remote file onto your computer" print "mirror - download all the file on the FTP" print "history - show the history you have logined into." continue else: print "Sorry, invalid command. Please enter 'help' for help." continue
************V 0.3Beta版本************
1.完善了History功能(仍然有小Bug正在解决中)
2.改变了登录的一些细节。
3.完善了回到上一级目录的代码
#!/usr/bin/python'''Created on 2011-11-5@author: zavierxuThis software is a simple FTP client, you can use it to login to your FTP server,download , upload your files. '''from ftplib import FTPimport sys, os,os.path,operatordef download(handle,filename): df = open(filename,"wb") try: handle.retrbinary("RETR " + filename,df.write) except Exception: print "Error in downloading the remote file." return else: print "Successful download!" df.close() returndef upload(handle,filename): uf = open(filename,"rb") (base,ext) = os.path.splitext(filename) try: handle.storbinary("STOR " + filename,uf) except Exception: print "Successful upload." else: print "Successful upload." uf.close() returnprint "This is a simple FTP Slient. You can use it to upload and download"f=file('history.txt','w')f.close()showhis=raw_input ("Would you like to see the history you logged in? yes/no :")if showhis == 'yes': f = file('history.txt') j = 0 for line in f: j += 1 print (str(j) + '.' + line) while 1: if j == 0: print "There is no login history." break else: i = 0 whichline=raw_input ("Enter the number you would like to login.(Enter 0 to quit.):") if whichline == '0': sys.exit() elif whichline > j & whichline < 0: print "Out of the range." continue else: while i < whichline: i += 1 lineread = f.readline() host_name = lineread f.close()elif showhis == 'no': host_name= raw_input ("Please enter the hostname.(For Example: public.sjtu.edu.cn)\nFTP address:") fin=file('history.txt') i=0 while 1: linein=fin.readline() if len(line) == 0: break if host_name == linein: i=1; break if i == 0: fout=file('history.txt','a') fout.write(host_name) fout.close()host_name = host_name.replace("\n","")user = raw_input("Enter username: ")pwd = raw_input("Enter password: ") try: ftph = FTP(host_name) except: print "Host could not be resolved." raw_input() sys.exit() else: pass try: ftph.login(user,pwd) except Exception: if user == "anonymous" or user == "Anonymous" and pwd == "anonymous" or pwd == "Anonymous": print "The server does not accept anonymous requests." raw_input() sys.exit() else: print "Invalid login combination." raw_input() sys.exit() else: print "Successfully connected!\n"print ftph.getwelcome()path = ftph.pwd()charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"print "Press help at any time to see proper usage.\n"while 1: command = raw_input("FTP ]> ") if "get " in command: rf = command.replace("get ","") rf = rf.replace("\n","") download(ftph,rf) continue elif "put " in command: lf = command.replace("put ","") lf = lf.replace("\n","") upload(ftph,lf) ftph.close() ftph = FTP(host_name) ftph.login(user,pwd) continue elif "mkdir " in command: mkdirname = command.replace("mkdir ","") mkdirname = mkdirname.replace("\n","") try: ftph.mkd(mkdirname) except: print "Incorrect usage." continue else: print "Directory created." continue elif "rmdir " in command: rmdirname = command.replace("rmdir ","") rmdirname = rmdirname.replace("\n","") current = ftph.pwd() ftph.cwd(rmdirname) allfiles = ftph.nlst() for file in allfiles: try: ftph.delete(file) except Exception: pass else: pass ftph.cwd(current) try: ftph.rmd(rmdirname) except Exception: print "All files within the directory have been deleted, but there is still another directory inside. As deleting this directory automatically goes against true FTP protocol, you must manually delete it, before you can delete the entire directory." else: print "Directory deleted." continue elif command == "pwd": print ftph.pwd() continue elif command == "ls": print ftph.dir() continue elif "cd " in command: dirpath = command.replace("cd ","") dirpath = dirpath.replace("\n","") try: ftph.cwd(dirpath) if dirpath=='..': print "Directory changed to " + ftph.pwd() elif dirpath=='.': print "Directory will not change." else: print "Directory changed to " + dirpath except: print "No such directory." continue elif command == "up": dir = ftph.pwd() temp = dir index = len(dir) - 1 for i in range(index,0,-1): if temp[i] == "/" and i != len(dir): ftph.cwd(temp) print "One directory back." continue if(operator.contains(charset,dir[i])): temp = temp[:-1] if temp=="/": ftph.cwd(temp) print "One directory back." elif command == "rename": fromname = raw_input("Current file name: ") toname = raw_input("To be changed to: ") ftph.rename(fromname,toname) print "Successfully renamed." continue elif "rm " in command: delfile = command.replace("rm ","") delfile = delfile.replace("\n","") ftph.delete(delfile) print "File successfully deleted." continue elif "size " in command: szfile = command.replace("size ","") szfile = szfile.replace("\n","") print "The file is " + str(ftph.size(szfile)) + " bytes." continue elif command == "quit": ftph.close() print "Session ended." break elif command == "history": fhis = file('history.txt') num = 0 for linehis in fhis: num += 1 print (str(num) + '.' + line) continue elif command == "help": print "size [filename] - returns the size in bytes of the specified file" print "quit - terminate the ftp session" print "rm [filename] - delete a file" print "rename - rename a file" print "up - navigate 1 directory up" print "cd [path] - change which directory you're in" print "pwd - prints the path of the directory you are currently in" print "ls - lists the contents of the directory" print "rmdir [directory path] - removes/deletes an entire directory" print "mkdir [directory path] - creates a new directory" print "put [filename] - stores a local file onto the server (does not work with microsoft office document types)" print "get [filename] - download a remote file onto your computer" print "mirror - download all the file on the FTP" print "history - show the history you have logined into." continue else: print "Sorry, invalid command. Please enter 'help' for help." continue
************V 0.2Beta版本************
1.修复了登录之后输入任何指令都只能跳转到显示目录的错误
2.修复了进入不存在的目录时程序的崩溃
3.修复了help选项中显示帮助信息格式错误,并且完善了help的功能
4.取消了完全输出登录信息的功能,方便阅读
5.一些其他的bug修复。
6.仍需要改进的功能:
1)访问目录时GBK模式编码输出时会乱码
2)mirror功能和history功能
3)Tab补全功能4)图形化界面
#!/usr/bin/python'''Created on 2011-11-5@author: zavierxuThis software is a simple FTP client, you can use it to login to your FTP server,download , upload your files. '''from ftplib import FTPimport sys, os,os.path,operatordef download(handle,filename): df = open(filename,"wb") try: handle.retrbinary("RETR " + filename,df.write) except Exception: print "Error in downloading the remote file." return else: print "Successful download!" df.close() returndef upload(handle,filename): uf = open(filename,"rb") (base,ext) = os.path.splitext(filename) try: handle.storbinary("STOR " + filename,uf) except Exception: print "Successful upload." else: print "Successful upload." uf.close() returnprint "This is a simple FTP Slient. You can use it to upload and download"host_name= raw_input ("Please enter the hostname.(For Example: public.sjtu.edu.cn)\nFTP address:")host_name = host_name.replace("\n","")user = raw_input("Enter username: ")pwd = raw_input("Enter password: ")try: ftph = FTP(host_name)except: print "Host could not be resolved." raw_input() sys.exit()else: passtry: ftph.login(user,pwd)except Exception: if user == "anonymous" or user == "Anonymous" and pwd == "anonymous" or pwd == "Anonymous": print "The server does not accept anonymous requests." raw_input() sys.exit() else: print "Invalid login combination." raw_input() sys.exit()else: print "Successfully connected!\n"print ftph.getwelcome()path = ftph.pwd()charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"print "Press help at any time to see proper usage.\n"while 1: command = raw_input("FTP ]> ") if "get " in command: rf = command.replace("get ","") rf = rf.replace("\n","") download(ftph,rf) continue elif "put " in command: lf = command.replace("put ","") lf = lf.replace("\n","") upload(ftph,lf) ftph.close() ftph = FTP(host_name) ftph.login(user,pwd) continue elif "mkdir " in command: mkdirname = command.replace("mkdir ","") mkdirname = mkdirname.replace("\n","") try: ftph.mkd(mkdirname) except: print "Incorrect usage." continue else: print "Directory created." continue elif "rmdir " in command: rmdirname = command.replace("rmdir ","") rmdirname = rmdirname.replace("\n","") current = ftph.pwd() ftph.cwd(rmdirname) allfiles = ftph.nlst() for file in allfiles: try: ftph.delete(file) except Exception: pass else: pass ftph.cwd(current) try: ftph.rmd(rmdirname) except Exception: print "All files within the directory have been deleted, but there is still another directory inside. As deleting this directory automatically goes against true FTP protocol, you must manually delete it, before you can delete the entire directory." else: print "Directory deleted." continue elif command == "pwd": print ftph.pwd() continue elif command == "ls": print ftph.dir() continue elif "cd " in command: dirpath = command.replace("cd ","") dirpath = dirpath.replace("\n","") try: ftph.cwd(dirpath) if dirpath=='..': print "Directory changed to " + ftph.pwd() elif dirpath=='.': print "Directory will not change." else: print "Directory changed to " + dirpath except: print "No such directory." continue elif command == "up": dir = ftph.pwd() temp = dir index = len(dir) - 1 for i in range(index,0,-1): if temp[i] == "/" and i != len(dir): ftph.cwd(temp) print "One directory back." continue if(operator.contains(charset,dir[i])): temp = temp[:-1] if temp=="/": ftph.cwd(temp) print "One directory back." elif command == "rename": fromname = raw_input("Current file name: ") toname = raw_input("To be changed to: ") ftph.rename(fromname,toname) print "Successfully renamed." continue elif "rm " in command: delfile = command.replace("rm ","") delfile = delfile.replace("\n","") ftph.delete(delfile) print "File successfully deleted." continue elif "size " in command: szfile = command.replace("size ","") szfile = szfile.replace("\n","") print "The file is " + str(ftph.size(szfile)) + " bytes." continue elif command == "quit": ftph.close() print "Session ended." break elif command == "help": print "size [filename] - returns the size in bytes of the specified file" print "quit - terminate the ftp session" print "rm [filename] - delete a file" print "rename - rename a file" print "up - navigate 1 directory up" print "cd [path] - change which directory you're in" print "pwd - prints the path of the directory you are currently in" print "ls - lists the contents of the directory" print "rmdir [directory path] - removes/deletes an entire directory" print "mkdir [directory path] - creates a new directory" print "put [filename] - stores a local file onto the server (does not work with microsoft office document types)" print "get [filename] - download a remote file onto your computer" print "mirror - download all the file on the FTP" print "history - show the history you have logined into." continue else: print "Sorry, invalid command. Please enter 'help' for help." continue
************V 0.1Beta初始版本************
#!/usr/bin/python
'''Created on 2011-11-5@author: zavierxuThis software is a simple FTP client, you can use it to login to your FTP server,download , upload your files. '''from ftplib import FTPimport sys, os,os.path,operatordef download(handle,filename): df = open(filename,"wb") try: handle.retrbinary("RETR " + filename,df.write) except Exception: print "Error in downloading the remote file." return else: print "Successful download!" df.close() returndef upload(handle,filename): uf = open(filename,"rb") (base,ext) = os.path.splitext(filename) try: handle.storbinary("STOR " + filename,uf) except Exception: print "Successful upload." else: print "Successful upload." uf.close() returnprint "This is a simple FTP Slient. You can use it to upload and download"host_name= raw_input ("Please enter the hostname.(For Example: public.sjtu.edu.cn)\nFTP address:")host_name = host_name.replace("\n","")user = raw_input("Enter username: ")pwd = raw_input("Enter password: ")try: ftph = FTP(host_name)except: print "Host could not be resolved." raw_input() sys.exit()else: passtry: ftph.login(user,pwd)except Exception: if user == "anonymous" or user == "Anonymous" and pwd == "anonymous" or pwd == "Anonymous": print "The server does not accept anonymous requests." raw_input() sys.exit() else: print "Invalid login combination." raw_input() sys.exit()else: print "Successfully connected!\n"print ftph.getwelcome()path = ftph.pwd()charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"print "Press help at any time to see proper usage.\n"ftph.set_debuglevel(2)while 1: command = raw_input("FTP ]> ") if "get " in command: rf = command.replace("get ","") rf = rf.replace("\n","") download(ftph,rf) continue elif "put " in command: lf = command.replace("put ","") lf = lf.replace("\n","") upload(ftph,lf) ftph.close() ftph = FTP(host_name) ftph.login(user,pwd) continue elif "mkdir " in command: mkdirname = command.replace("mkdir ","") mkdirname = mkdirname.replace("\n","") try: ftph.mkd(mkdirname) except: print "Incorrect usage." continue else: print "Directory created." continue elif "rmdir " in command: rmdirname = command.replace("rmdir ","") rmdirname = rmdirname.replace("\n","") current = ftph.pwd() ftph.cwd(rmdirname) allfiles = ftph.nlst() for file in allfiles: try: ftph.delete(file) except Exception: pass else: pass ftph.cwd(current) try: ftph.rmd(rmdirname) except Exception: print "All files within the directory have been deleted, but there is still another directory inside. As deleting this directory automatically goes against true FTP protocol, you must manually delete it, before you can delete the entire directory." else: print "Directory deleted." continue elif command == "dir" or "ls": print ftph.dir() continue elif command == "pwd": print ftph.pwd() continue elif "cd " in command: dirpath = command.replace("cd ","") dirpath = dirpath.replace("\n","") ftph.cwd(dirpath) print "Directory changed to " + dirpath continue elif command == "cd..": dir = ftph.pwd() temp = dir index = len(dir) - 1 for i in range(index,0,-1): if temp[i] == "/" and i != len(dir): ftph.cwd(temp) print "One directory back." continue if(operator.contains(charset,dir[i])): temp = temp[:-1] if temp=="/": ftph.cwd(temp) print "One directory back." elif command == "rename": fromname = raw_input("Current file name: ") toname = raw_input("To be changed to: ") ftph.rename(fromname,toname) print "Successfully renamed." continue elif "rm " in command: delfile = command.replace("rm ","") delfile = delfile.replace("\n","") ftph.delete(delfile) print "File successfully deleted." continue elif "size " in command: szfile = command.replace("size ","") szfile = szfile.replace("\n","") print "The file is " + str(ftph.size(szfile)) + " bytes." continue elif command == "quit": ftph.close() print "Session ended." break elif command == "help": print "size [filename] - returns the size in bytes of the specified file" print "quit - terminate the ftp session\n" print "rm [filename] - delete a file\n" print "rename - rename a file\n" print "cd.. - navigate 1 directory up\n" print "cd [path] - change which directory you're in\n" print "pwd - prints the path of the directory you are currently in\n" print "dir - lists the contents of the directory\n" print "ls - lists the contents of the directory\n" print "rmdir [directory path] - removes/deletes an entire directory\n" print "mkdir [directory path] - creates a new directory\n" print "put [filename] - stores a local file onto the server (does not work with microsoft office document types)\n" print "get [filename] - download a remote file onto your computer\n\n" print "mirror - download all the file on the FTP" print "history - show the history you have logined into." continue else: print "Sorry, invalid command. Please enter 'help' for help." continue
- Python 编写 FTP Client
- Python编写FTP下载程序
- ftp client
- FTP Client
- ftp client
- ftp client
- FTP服务器和客户端源代码编写问题(ftp server client source)
- FTP服务器和客户端源代码编写问题(ftp server client source)
- 用python编写ftp客户端程序
- Python编写的的ftp文件上传
- 使用python内建asyncore编写socket client
- Ftp Client(java)
- FTP Server/Client
- write FTP client
- FTP client程序
- filezilla ftp client
- FTP Client enterLocalPassiveMode
- ftp client api
- 预编译头文件的问题
- 两个有序数组找第n个数
- SAP 甘特图
- Javascript中的陷阱大集合
- spring管理abatis
- Python 编写 FTP Client
- grep的语法和用法
- Windows CE USB摄像头驱动编写
- LVS + keepalived 实现负载均衡
- 详解C/C++预处理器
- vi的具体使用方法与命令
- 【杂谈】【转载】卡尔曼滤波简介及其算法实现代码
- 无法解析FileNameExtensionFilter
- 枚举的取值范围