python server代码:
from pyftpdlib.servers import FTPServer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.authorizers import DummyAuthorizer
class FTP_Server():
def init(self):
handler = FTPHandler # handler is a class(type is ‘type’)
ip = ‘127.0.0.1’
port = 21
address = (ip, port)
self.ftpServer = FTPServer(address, handler)
self.ftpServer.max_cons = 150 # max connection numbers
self.ftpServer.max_cons_per_ip = 10 # max connection ip numbers
print(‘FTP server created’)
print(self.ftpServer)
# Change welcome info when client logined in
self.ftpServer.handler.banner = ‘Welcome to my FTP server.’
# Passive port number should be more than max ip number, otherwise may course connection failed
self.ftpServer.handler.passive_ports = range(2000, 2333)
# User info bin
self.userInfo = {'User_1': {'user_name': 'Admin',
'password': '888888',
'home_path': '.\\FTPServerFile',
'permission': 'elradfmwM',
'msg_login': 'Admin login successful',
'msg_quit': 'Goodbye, admin.'},
'User_2': {'user_name': 'Customer',
'password': '777777',
'home_path': '.\\FTPServerFile',
'permission': 'elr',
'msg_login': 'Customer login successful',
'msg_quit': 'Goodbye, customer.'}}
def addUser(self):
# Add users method_1
authorizer = DummyAuthorizer()
# Add new user, user name, password, home path('.' is current root path), permission level
for user in self.userInfo.values():
authorizer.add_user(user['user_name'], user['password'], user['home_path'],
perm=user['permission'], msg_login=user['msg_login'], msg_quit=user['msg_quit'])
self.ftpServer.handler.authorizer = authorizer
# Add users method_2
# Mark here: handler.authorizer also generate from DummyAuthorizer inside Handler module
# for user in self.userInfo.values():
# self.ftpServer.handler.authorizer.add_user(user['user_name'], user['password'], user['home_path'],
# perm=user['permission'], msg_login=user['msg_login'], msg_quit=user['msg_quit'])
# Add anonymous
authorizer.add_anonymous('.\\FTPServerFile',perm='elr', msg_login='anonymous login successful', msg_quit='Goodbye, anonymous.')
def run(self):
print('FTP server start')
self.ftpServer.serve_forever()
def stop(self):
self.ftpServer.close_all()
ftp_server = FTP_Server()
ftp_server.addUser()
ftp_server.run()
python client代码:
coding=gbk
from ftplib import FTP
import os
import sys
_XFER_FILE = ‘FILE’
_XFER_DIR = ‘DIR’
class FTP_Client():
def init(self):
# Info for FTP client
ftp_server = ‘127.0.0.1’
ftp_port = 21
# user_name = ‘Customer’
# password = ‘777777’
user_name = ‘Admin’
password = ‘888888’
# user_name = ”
# password = ”
# Create FTP
self.ftp = FTP()
# set ftp debuglevel here, default is 0
self.ftp.set_debuglevel(1)
self.ftp.connect(ftp_server, ftp_port)
self.ftp.login(user_name, password)
self.ftp.set_pasv(False)
print('<<< Welcome info:', self.ftp.getwelcome())
def uploadDir(self, localdir='./', remotedir='./'):
if not os.path.isdir(localdir):
return
self.ftp.cwd(remotedir)
for file in os.listdir(localdir):
src = os.path.join(localdir, file)
if os.path.isfile(src):
self.uploadFile(src, file)
elif os.path.isdir(src):
try:
self.ftp.mkd(file)
except:
sys.stderr.write('the dir is exists %s'%file)
self.uploadDir(src, file)
self.ftp.cwd('..')
def uploadFile(self, localpath, remotepath='./'):
if not os.path.isfile(localpath):
return
print ('+++ upload %s to %s'%(localpath, remotepath))
self.ftp.storbinary('STOR ' + remotepath, open(localpath, 'rb'))
def __filetype(self, src):
if os.path.isfile(src):
index = src.rfind('\\')
if index == -1:
index = src.rfind('/')
return _XFER_FILE, src[index+1:]
elif os.path.isdir(src):
return _XFER_DIR,''
def upload(self, src):
filetype, filename = self.__filetype(src)
if filetype == _XFER_DIR:
self.srcDir = src
self.uploadDir(self.srcDir)
elif filetype == _XFER_FILE:
self.uploadFile(src, filename)
def downloadFile(self,filepath):
bufsize = 1024
downList = ['FTPClient.py']
# Create an new file to store data received
for down in downList:
file_handler = open('FTPClientFile\\%s' % down, 'wb').write
# retrbinary need 3 para at least,
# 1st is RETR+dirName, dirName is target file name,
# 2nd is a write function, will be called inside function, open a new file in client to store file data,
# 3rd is bufsize.
self.ftp.retrbinary('RETR %s' % down, file_handler, bufsize)
def get_dirs_files(self):
u''' 得到当前目录和文件, 放入dir_res列表 '''
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 walk(self, next_dir):
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('%s' % 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)
def run(self):
os.chdir(os.getcwd()+'./FTPClientFile')
self.walk('.')
def quit(self):
self.ftp.quit()
# This function can get all the contains info in server path
def showDir(self):
self.ftp.dir()
# All this below function should base on the directory set in server.
# Make a new directory
def newDir(self, dir='.\\FTPtest'):
self.ftp.mkd(dir)
# Change working directory
def changeDir(self, dir='.\\FTPtest'):
self.ftp.cwd(dir)
# Return current working directory(base is '/')
def presentDir(self):
self.ftp.pwd()
# Remove certain directory
def removeDir(self, dir='.\\FTPtest'):
self.ftp.rmd(dir)
# Delete file
def delFile(self, fileName):
self.ftp.delete(fileName)
# Rename file
def renameFile(self, currName='getmakefile.py', reName='FTPClient.py'):
self.ftp.rename(currName, reName)
if name == ‘name‘:
ftp_client = FTP_Client()
ftp_client.upload(‘./FTPClientFile’)
ftp_client.run()
ftp_client.downloadFile()
#ftp_client.renameFile()
#ftp_client.newDir()
#ftp_client.changeDir()
#ftp_client.removeDir()
ftp_client.quit()