1 #!/user/bin/python 2 #coding=utf-8 3 4 import ftplib 5 import os 6 import socket 7 8 HOST = 'ftp.kernel.org' 9 DIRN = 'pub/linux/kernel' 10 FILE = 'README' 11 12 def main(): 13 try: 14 f = ftplib.FTP(HOST) 15 except(socket.error,socket.gaierror) as e: 16 print "Error:cannot reach '%s'"%HOST 17 return 18 print " connected to host '%s'"%HOST 19 20 try: 21 f.login() 22 except ftplib.error_perm: 23 print "Error:cannot login anonymously" 24 f.quit() 25 return 26 print " Login as anonymous." 27 28 try: 29 f.cwd(DIRN) 30 except ftplib.error_perm: 31 print "Error:cannot CD to '%s'"%DIRN 32 f.quit() 33 return 34 print " changed to '%s'"%DIRN 35 36 try: 37 f.retrbinary('RETR %s'%FILE,open(FILE,"wb").write) 38 except ftplib.error_perm: 39 print "Error:cannot read file '%s'"%FILE 40 os.unlink(FILE) 41 else: 42 print " Download '%s' to cwd"%FILE 43 f.quit() 44 45 if __name__=="__main__": 46 main()
1 #!/usr/bin/python 2 #coding=utf-8 3 4 #上传文件 5 from ftplib import FTP 6 import sys,getpass,os.path 7 8 host,username,localfile,remotepath = sys.argv[1:] 9 10 password=getpass.getpass("Enter password for %s on %s"%(username,host)) 11 f=FTP(host) 12 f.login(username,password) 13 print remotepath 14 f.cwd(remotepath) 15 print f.dir() 16 print localfile 17 fd=open(localfile,'rb') 18 f.storbinary('STOP test',fd) 19 fd.close() 20 f.quit() 21 22 if __name__=="__main__": 23 main()