Python连接ftp服务器上传下载文件,以下是具体代码:
from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from pyftpdlib.servers import FTPServer from ftplib import FTP import time,tarfile,os # 创建一个ftp服务器 def creatFtp(): # 实例化DummyAuthorizer来创建ftp用户 authorizer = DummyAuthorizer() # 参数:用户名,密码,目录,权限 authorizer.add_user('qdftpserver', 'admin@1234', r'D:\software', perm='elradfmwMT') # 匿名登录 # authorizer.add_anonymous('/homebody') handler = FTPHandler handler.authorizer = authorizer # 参数:IP,端口,handler server = FTPServer(('192.168.1.112', 2121), handler) #设置为0.0.0.0为本机的IP地址 server.serve_forever() # 连接ftp # host:IP地址 # port:int类型的端口号 def ftpconnect(host,port, username, password): ftp = FTP() # 打开调试级别2,显示详细信息 #ftp.set_debuglevel(2) ftp.connect(host, port) ftp.login(username, password) return ftp # 从ftp下载文件 # ftp:已连接的ftp # ftp_w:设置FTP当前操作的路径,就是子目录文件;空字符则默认当前 # localpath:下载到本地的目录文件夹 def downloadfile(ftp,ftp_w ,localpath): try: #设置的缓冲区大小 ftp.cwd(ftp_w) # 设置FTP当前操作的路径,就是子目录文件;空则默认当前 bufsize = 1024 files = ftp.nlst() for i in range(len(files)): remotepath = files[i] name = files[i] path = os.path.join(localpath, name) fp = open(path, 'wb') ftp.retrbinary('RETR ' + remotepath, fp.write, bufsize) ftp.delete(remotepath) fp.close() #ftp.set_debuglevel(0)# 参数为0,关闭调试模式 except IOError as e: print(str(e)) # 从本地上传文件到ftp def uploadfile(ftp, ftp_w, localpath): ftp.cwd(ftp_w) # 设置FTP当前操作的路径,就是子目录文件;空则默认当前 bufsize = 1024 fileList = os.listdir(localpath) for i in range(len(fileList)): path = os.path.join(localpath, fileList[i]) fp = open(path, 'rb') ftp.storbinary('STOR ' + fileList[i], fp, bufsize) fp.close() if __name__ == '__main__': ftp = ftpconnect("192.168.1.116",21,"admin","123456") #downloadfile(ftp,"/1",r"D:\xj\测试数据1") uploadfile(ftp,"/test1",r"D:\xj\测试数据1")