from ftplib import FTP ftp=FTP() #设置变量 ftp.set_debuglevel(2) #打开调试级别2,显示详细信息 ftp.connect("IP","port") #连接的ftp sever和端口 ftp.login("user","password")#连接的用户名,密码 print ftp.getwelcome() #打印出欢迎信息 ftp.cmd("xxx/xxx") #更改远程目录 bufsize=1024 #设置的缓冲区大小 filename="filename.txt" #需要下载的文件 file_handle=open(filename,"wb").write #以写模式在本地打开文件 ftp.retrbinaly("RETR filename.txt",file_handle,bufsize) #接收服务器上文件并写入本地文件 ftp.set_debuglevel(0) #关闭调试模式 ftp.quit #退出ftp ftp相关命令操作 ftp.cwd(pathname) #设置FTP当前操作的路径 ftp.dir() #显示目录下文件信息 ftp.nlst() #获取目录下的文件 ftp.mkd(pathname) #新建远程目录 ftp.pwd() #返回当前所在位置 ftp.rmd(dirname) #删除远程目录 ftp.delete(filename) #删除远程文件 ftp.rename(fromname, toname)#将fromname修改名称为toname。 ftp.storbinaly("STOR filename.txt",file_handel,bufsize) #上传目标文件 ftp.retrbinary("RETR filename.txt",file_handel,bufsize)#下载FTP文件
实际的例子:
# -*- coding: utf-8 -*- import ftplib import os import socket HOST = 'ftp.mozilla.org' DIRN = 'pub/mozilla.org/webtools' FILE = 'bugzilla-3.6.7.tar.gz' 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 "anonymously"' try: f.cwd(DIRN) except ftplib.error_perm: print 'ERRORL cannot CD to "%s"' % DIRN f.quit() return print '*** Changed to "%s" folder' % DIRN try: #传一个回调函数给retrbinary() 它在每接收一个二进制数据时都会被调用 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()