【实例简介】修改如下图的ftp信息 为您的ftp信息,即可实现ftp文件下载
【实例截图】
执行界面如下:
下载结果如下:
【核心代码】
#!/usr/bin/python
import ftplib
import os
import socket
HOST = 'ftp.mozilla.org'
DIRN = 'pub/mozilla.org/webtools'
FILE = 'bugzilla-LATEST.tar.gz'
def main():
try:
f = ftplib.FTP(HOST)
except (socket.error,socket.gaierror) as e:
print( 'ERROR:cannot reach "%s"' % HOST)
return
print('*** Connected to host "%s"' % HOST)
try:
f.login('web2','passwd')
except ftplib.error_perm:
print( 'ERROR: cannot login anonymously')
f.quit()
return
print('*** Logged in as "anonymous"')
try:
f.cwd(DIRN)
except ftplib.error_perm:
print('ERROR:cannot CD to "%s"' % DIRN)
f.quit()
return
print('*** Changed to "%s" folder' % DIRN)
try:
f.retrbinary('RETR %s' % FILE,
open(FILE,'wb').write)
except ftplib.error_perm:
print('ERROR:cannot read file "%s"' % FILE)
if os.path.exists(FILE):
os.unlink(FILE)
else:
print( '*** Downloaded "%s" to CWD' % FILE)
f.quit()
if __name__ == '__main__':
main()