Python中默认安装的ftplib模块定义了FTP类,其中函数有限,可用来实现简单的ftp客户端,用于上传或下载文件
FTP的工作流程及基本操作可参考协议RFC959
ftp登陆连接
from ftplib import FTP #加载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文件
from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from pyftpdlib.servers import FTPServer from CFileOperator import CFileOperator import ftplib import os import thread import time import socket class CFTPServer(): def __init__(self, name="song", passwd="song", port=21): self._name = name self._passwd = passwd self._port = port def Start(self): authorizer = DummyAuthorizer() authorizer.add_user(self._name, self._passwd, '.', perm='elradfmwM') authorizer.add_anonymous(os.getcwd()) handler = FTPHandler handler.authorizer = authorizer handler.banner = "pyftpdlib based ftpd ready." address = ('', self._port) self._server = FTPServer(address, handler) self._server.max_cons = 256 self._server.max_cons_per_ip = 5 self._server.serve_forever() def Stop(self): self._server.close_all() class CFTPCLient(): def __init__(self, host="127.0.0.1", name="song", passwd="song", port=21,savepath='./'): self._host = host self._name = name self._passwd = passwd self._port = port self._ftp = None self._connet = False self._buffer = 2048 self._FileOperator = CFileOperator() self._savepath=savepath self._srcpath=os.getcwd() def conneterver(self): try: self._ftp = ftplib.FTP(self._host) except (socket.error, socket.gaierror), e: print 'ERROR: cannot reach "%s"' % self._host self._connet = False return print '*** Connected to host "%s"' % self._host try: self._ftp.login(self._name, self._passwd) except ftplib.error_perm: print 'ERROR: login failed with "%s" and "%s"' % self._name, self._passwd self._ftp.quit() self._connet = False return self._ftp.cwd('./') self._ftp.nlst() print '*** Logged in' self._connet = True def CmdPath(self,path): if not self._connet: self.conneterver() if not self._connet: return self._ftp.cwd(path) def GetCur(self): if not self._connet: self.conneterver() if not self._connet: return return self._ftp.pwd() def List(self): if not self._connet: self.conneterver() if not self._connet: return self._ftp.dir() def UPLoadFile(self, filename): if not self._connet: self.conneterver() if not self._connet: return elem = filename if self._FileOperator.ISDirExit(filename): self._FileOperator.TarFile(filename) elem += ".tar" file_open = open(elem, 'rb') self._ftp.storbinary('STOR %s' % os.path.basename(elem), file_open, self._buffer) if not file_open.closed: file_open.close() def DeleteRomoteFile(self,filename): if not self._connet: self.conneterver() if not self._connet: return self._ftp.delete(filename) def DeleteRomoteDir(self,Dir): if not self._connet: self.conneterver() if not self._connet: return self._ftp.rmd(Dir) def RenameRomoteFile(self,oldname,newname): if not self._connet: self.conneterver() if not self._connet: return self._ftp.rename(oldname,newname) def get_dirs_files(self): dir_res = [] self._ftp.dir('.', dir_res.append) files = [f.split(None, 8)[-1] for f in dir_res if f.startswith('-')] dirs = [f.split(None, 8)[-1] for f in dir_res if f.startswith('d')] return (files, dirs) def DownLoadFile(self, next_dir): if not self._connet: self.conneterver() if not self._connet: return print 'Walking to', next_dir self._ftp.cwd(next_dir) try: os.mkdir(next_dir) except OSError: pass os.chdir(next_dir) ftp_curr_dir = self._ftp.pwd() local_curr_dir = os.getcwd() files, dirs = self.get_dirs_files() print "FILES: ", files print "DIRS: ", dirs for f in files: print next_dir, ':', f outf = open(f, 'wb') try: self._ftp.retrbinary('RETR %s' % f, outf.write) finally: outf.close() for d in dirs: os.chdir(local_curr_dir) self._ftp.cwd(ftp_curr_dir) self.walk(d) if __name__ == '__main__': c = CFTPServer() thread.start_new_thread(c.Start, ()) d = CFTPCLient() time.sleep(2) d.UPLoadFile("/home/test") time.sleep(3000) #d.UPLoadFile("/home/test") # d.DownLoadFile("/test.tar") # f =CFileOperator() #f.TarFile("/home/test")