用python寫一個小型的FTP客戶端軟體
阿新 • • 發佈:2019-01-07
第一次用Python語言寫的程式,功能可以基本實現,還有很多不足的地方,需要改進。
#!/usr/local/env python #-*- coding:UTF-8 -*- import ftplib import os import socket #HOST='192.168.203.100' DIRN='/home/ftpadmin' FILE='test.txt' def download(f): try: f.cwd(DIRN) except ftplib.error_perm: print 'ERROR:Cannot CD to %s ' % DIRN f.quit() return file=raw_input("請選擇要下載的檔案:") try: f.retrlines('RETR %s' % file,open(file,'wb').write) except ftplib.error_perm: print 'ERROR:cannot read file %s' % file os.unlink(file) else: print "***Download %s tp CWD " % file return def put(f): filepath=raw_input("請輸入要上傳的檔名:") f1=open(filepath,'rb') file_name=os.path.split(filepath)[-1] try: f.storlines('STOR %s' % file_name,f1) except ftplib.error_perm: f.quit() return def show(f): f.dir() def quit1(f): print "退出程式" f.quit() order={'d':download,'p':put,'s':show} def main(): HOST=raw_input( "請輸入要登入的伺服器地址:") try: f=ftplib.FTP(HOST) except (socket.error,socket.gaierror),e: print "ERROR:cannot reache %s" % HOST return print "...connected to host %s " % HOST try: f.login('ftpadmin','12345') except ftplib.error_perm: print 'ERROR:cannot login FTP' f.quit() return print "成功登陸FTP伺服器" print "請選擇操作的服務" showmenu(f) def showmenu(f): s=""" (D)ownload (P)put (s)how (Q)uit Enter choice: """ done=False while not done: chosen=False while not chosen: try: choice=raw_input(s).strip()[0].lower() except (EOFError,KeyboardInterrupt): print "異常,退出伺服器" choice='q' print "你的選擇是:%s" % choice if choice not in 'dpqs': print "invaid option,try again" else: chosen=True if choice=='q': quit1(f) break order[choice](f) if __name__=='__main__': main()