FTP连接与下载(Python)

#encoding:utf-8
import ftplib
import os
import socket

HOST='ftp.pku.edu.cn'#服务器地址
DIRN='Linux/boot.kernel.org/'#下载目录
FILE='gpxe.iso'#下载的文件名

def main():
    try:
        f=ftplib.FTP(HOST)
    except(socket.error,socket.gaierror):
        print 'ERROR:cannot reach "%s"'%HOST
        return
    print '*** Connected 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(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
        os.unlink(FILE)
    else:
        print '*** Downloaded "%s" to CWD'%FILE
    f.quit()
    return

if __name__=='__main__':
    main()
 

你可能感兴趣的:(python,ftp)