python访问ftp站点——切换访问模式。
在一个控制连接下,切换主动模式和被动模式访问ftp站点。
1 #!/usr/bin/python 2 # -*- coding: utf-8 -*- 3 import ftplib 4 import os 5 import socket 6 import sys 7 8 HOST = '10.15.26.51' 9 DIRN = 'file_yes' 10 FILE = 'wordless10m.docx' 11 FILE1 = 'ftp1.py' 12 def main(): 13 try: 14 f = ftplib.FTP(HOST) 15 except (socket.error, socket.gaierror): 16 print 'ERROR:cannot reach " %s"' % HOST 17 return 18 19 print '***Connected to host "%s"' % HOST 20 21 try: 22 f.login('FTP002','&&&&&&&') 23 except ftplib.error_perm: 24 print 'ERROR: cannot login FTP' 25 f.quit() 26 return 27 #print f.getwelcome() 28 print '*** Logged in as FTP002' 29 30 try: 31 f.set_pasv(1)#pasv mode 32 except ftplib.error_perm: 33 print "cannot changed mode" 34 f.quit() 35 return 36 #print "***active mode" 37 print "***pasv mode" 38 39 40 41 try: 42 f.cwd(DIRN) 43 except ftplib.error_perm: 44 print 'ERRORL cannot CD to "%s"' % DIRN 45 f.quit() 46 return 47 print '*** Changed to "%s" folder' % DIRN 48 49 try: 50 f.dir() 51 except ftplib.error_perm: 52 print 'ERRORL list "%s" info' % DIRN 53 f.quit() 54 return 55 print '*** This is "%s" folder info' % DIRN 56 57 58 try: 59 buf_size = 1024 60 os.chdir("c:/share/") 61 f.retrbinary('RETR %s' %FILE, open(FILE, 'wb').write,buf_size) 62 #f.retrbinary('RETR wordless10m.docx', open(FILE, 'wb').write,buf_size) 63 except ftplib.error_perm: 64 print 'ERROR: cannot read file "%s"' % FILE 65 os.unlink(FILE) #delete FILE 66 else: 67 print '*** Downloaded "%s" to CWD' % FILE 68 69 try: 70 f.set_pasv(0)#active mode 71 except ftplib.error_perm: 72 print "cannot changed mode" 73 f.quit() 74 return 75 print "***active mode" 76 #print "***pasv mode" 77 78 79 80 try: 81 buf_size = 1024 82 #f.retrbinary('RETR %s' %FILE, open(FILE, 'wb').write,buf_size) 83 f.storbinary('stor %s'%FILE1, open(FILE1, 'rb'),buf_size) 84 except ftplib.error_perm: 85 print 'ERROR: cannot read file "%s"' % FILE1 86 #os.unlink(FILE1) #delete FILE 87 else: 88 print '*** Uploaded "%s" to CWD' % FILE1 89 try: 90 f.dir() 91 except ftplib.error_perm: 92 print 'ERRORL list "%s" info' % DIRN 93 f.quit() 94 return 95 print '*** This is "%s" folder info' % DIRN 96 f.quit() 97 return 98 99 if __name__ == '__main__': 100 main()