Python 里面的 FTP 连接,主要依赖 ftplib
这个模块,具体请看帮助文档。
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
|
import ftplib import os import socket HOST = 'ftp.mozilla.org' DIR = 'pub/mozilla.org/webtools' FILE = 'bugzilla-LATEST.tar.gz' def ftpDownload() : try: f = ftplib.FTP(HOST) except (socket.error, socket.gaierror), e: print 'ERROR: cannot connect "%s"' % HOST return print '>>Connect to host "%s"' % HOST try: f.login() except ftplib.error_perm: print 'ERROR: cannot login anonymously' f.quit() return print '>>Logged in as "anonymous"' try: f.cwd(DIR) except ftplib.error_perm: print 'ERROR: cannot go to "%s"' % DIR f.quit() return print '>>Go to "%s"' % DIR try: f.retrbinary('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"' % FILE f.quit() return def main() : ftpDownload() if __name__ == '__main__': main()
|