The Ftplib module, which is installed by default in Python, defines the FTP class , where functions are limited and can be used to implement a simple FTP client for uploading or downloading files, and the functions are listed below
FTP Login connection from ftplib import FTP #加载ftp模块ftp =ftp () #设置变量ftp. Set_debuglevel (2) #打开调试级别2, Show Details ftp.connect ("IP", "Port") #连接的ftp Sever and Port Ftp.login ("User", "password") #连接的用户名, password print ftp.get Welcome () #打印出欢迎信息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 () #退出ftpftp相关命令操 As 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文件
Example 1: Downloading and uploading files
#Coding:utf-8 fromFtplibImportFTPImport TimeImportTarfile#!/usr/bin/python#-*-coding:utf-8-*- fromFtplibImportFTPdefFtpconnect (host, username, password): FTP=FTP ()#Ftp.set_debuglevel (2) #打开调试级别2, show detailsFtp.connect (host, 21)#ConnectionFtp.login (username, password)#login, if anonymous login is replaced by an empty string returnFTPdefdownloadfile (FTP, RemotePath, localpath): BufSize= 1024#Set buffer block sizefp = open (LocalPath,'WB')#to open a file locally in write modeFtp.retrbinary ('RETR'+ RemotePath, Fp.write, bufsize)#receiving files on the server and writing to local filesFtp.set_debuglevel (0)#Turn off debuggingFp.close ()#Close FiledefUploadFile (FTP, RemotePath, localpath): BufSize= 1024FP= Open (LocalPath,'RB') Ftp.storbinary ('STOR'+ RemotePath, FP, bufsize)#Uploading Filesftp.set_debuglevel (0) fp.close ()if __name__=="__main__": FTP= Ftpconnect ("******","***","***") DownloadFile (FTP,"***","***") UploadFile (FTP,"***","***") Ftp.quit ()
Example 2: Uploading, downloading files/directories
#Coding:utf-8 fromcTYPESImport*ImportOSImportSYSImportFtplibclassmyftp:ftp=Ftplib. FTP () Bisdir=False Path="" def __init__(Self, host, port=' +'): #Self.ftp.set_debuglevel (2) #打开调试级别2, show details #SELF.FTP.SET_PASV (0) #0主动模式 1 #被动模式Self.ftp.connect (host, Port)defLogin (self, User, passwd): Self.ftp.login (User, passwd)PrintSelf.ftp.welcomedefDownLoadFile (self, LocalFile, remotefile): File_handler= Open (LocalFile,'WB') Self.ftp.retrbinary ("RETR%s"%(RemoteFile), File_handler.write) file_handler.close ()returnTruedefUploadFile (self, LocalFile, remotefile):ifOs.path.isfile (localfile) = =False:returnFalse File_handler= Open (LocalFile,"RB") Self.ftp.storbinary ('STOR%s'%remotefile, File_handler, 4096) File_handler.close ()returnTruedefUploadfiletree (self, Localdir, Remotedir):ifOs.path.isdir (localdir) = =False:returnFalsePrint "Localdir:", Localdir localnames=Os.listdir (Localdir)Print "list:", LocalnamesPrintremotedir self.ftp.cwd (remotedir) forLocalinchlocalnames:src=Os.path.join (Localdir, Local)ifOs.path.isdir (SRC): self. Uploadfiletree (SRC, Local)Else: Self. UploadFile (SRC, Local) self.ftp.cwd (".." ) return defDownloadfiletree (self, Localdir, Remotedir):Print "Remotedir:", RemotedirifOs.path.isdir (localdir) = =False:os.makedirs (Localdir) self.ftp.cwd (remotedir) remotenames=Self.ftp.nlst ()Print "Remotenames", RemotenamesPrintSelf.ftp.nlst ("/del1") forFileinchremotenames:local=os.path.join (localdir, file)ifself.isdir (file): Self. Downloadfiletree (Local, file)Else: Self. DownLoadFile (Local, file) self.ftp.cwd (".." ) return defShow (Self, list): Result= List.lower (). Split (" " ) ifSelf.pathinchResult and "<dir>" inchResult:self.bIsDir=Truedefisdir (self, path): Self.bisdir=False Self.path=Path#This ues callback function, that would change Bisdir valueSelf.ftp.retrlines ('LIST', Self.show)returnSelf.bisdirdefClose (self): Self.ftp.quit ()if __name__=="__main__": FTP= Myftp ('*****') Ftp.login ('***','***') Ftp.downloadfiletree ('del','/del1')#OKFtp.uploadfiletree ('del',"/del1") Ftp.close ()Print "ok!"
Note : The directory is a file, if the directory is not transmitted
Python ftplib module