python--FTP的实现(用socketserver)

1、要求

和上一篇FTP的实现(用socket)的要求一样,只是老师要求用socketserver来实现

 

2、思路

socketserver来实现的话,

(1)需要定义一个自己的handler类,该类继承于socketserver.BaseRequestHandler,然后重写父类的handle方法,在这个方法中实现具体的要求,就是原来用socket实现的server的功能,根据client的请求分别做出相应的动作。

(2)将主机、端口、自己的handler类作为参数,建立socketserver.TCPServer对象,然后serve_forever()

(3)其他代码都不变,参见上一篇用socket实现的FTP

  1 import socketserver
  2 import socket
  3 import os
  4 
  5 host='localhost'
  6 port=21
  7 
  8 class MyFtpServerHandler(socketserver.BaseRequestHandler):
  9     def handle(self):
 10         # 从文件获取用户名密码,放在字典里
 11         userinfo = {}
 12         fddir = os.path.dirname(os.path.dirname(__file__))  # project根目录
 13         homedir = fddir + '\homedir'
 14 
 15         with open(r'%s\userinfo\userinfo' % fddir, 'r', encoding='utf-8') as userfd:
 16             line = userfd.readline()
 17             while line:
 18                 name = line.split()[0]
 19                 passwd = line.split()[1]
 20                 userinfo[name] = passwd
 21                 line = userfd.readline()
 22 
 23         # 等待接收数据
 24         while True:
 25             print("server waiting...")
 26 
 27             while True:
 28                 clientdata = self.request.recv(1024)  # 1M data
 29                 clientdatastr = clientdata.decode('utf-8')
 30                 '''
 31                 分辨传进来的是什么命令做相应的处理
 32                 1、登录命令以loginstring开头--验证用户名密码是否正确
 33                 2、退出是exit或quit--关闭conn,退出接受命令的状态
 34                 3、其他
 35                 '''
 36                 if clientdatastr.startswith('loginstring'):
 37                     strlist = clientdatastr.split()
 38                     namein = strlist[1]
 39                     passin = strlist[2]
 40                     if namein in userinfo.keys() and userinfo[namein] == passin:
 41                         os.chdir('%s\homedir\%s' % (fddir, namein))
 42                         self.request.send(b'login success...')
 43                     else:
 44                         self.request.send(b'user name and password wrong......')
 45                         self.request.close()
 46                         break
 47                 elif clientdatastr == 'exit' or clientdatastr == 'quit':
 48                     self.request.close()
 49                     break
 50                 elif clientdatastr == 'currentdir':
 51                     curdir = os.getcwd()
 52                     self.request.send(curdir.encode('utf-8'))
 53                 elif clientdatastr == 'currentfiles':
 54                     curdir = os.getcwd()
 55                     returnstr = ''
 56                     for root, dirs, files in os.walk(curdir):
 57                         returnstr += 'rootdir:' + root + '\n'
 58                         for d in dirs:
 59                             returnstr += 'directory:' + d + '\n'
 60                         for f in files:
 61                             returnstr += 'file:' + f + '\n'
 62                     print(returnstr)
 63                     self.request.send(returnstr.encode('utf-8'))
 64                 elif clientdatastr.startswith('downdir'):
 65                     strlist = clientdatastr.split()
 66                     dirname = strlist[1]
 67                     targetdir = os.getcwd() + '\\' + dirname
 68                     os.chdir(targetdir)
 69                     curdir = os.getcwd()
 70                     self.request.send(curdir.encode('utf-8'))
 71                 elif clientdatastr == 'updir':
 72                     fatherdir = os.path.dirname(os.getcwd())
 73                     os.chdir(fatherdir)
 74                     curdir = os.getcwd()
 75                     self.request.send(curdir.encode('utf-8'))
 76                 elif clientdatastr.startswith('download'):
 77                     strlist = clientdatastr.split()
 78                     filename = strlist[1]
 79                     dirname = os.path.join(os.getcwd(), filename)
 80                     with open(dirname, 'r') as fd:
 81                         msg = fd.read()
 82                     self.request.send(msg)
 83                 elif clientdatastr.startswith('upload'):
 84                     strlist = clientdatastr.split()
 85                     filename = strlist[1]
 86                     filecont = strlist[2]
 87                     dir = os.path.join(os.getcwd(), filename)
 88                     with open(filename, 'w') as fd:
 89                         fd.write(filecont)
 90                     self.request.send('***')
 91                 else:
 92                     cmdstr = clientdatastr.strip()
 93                     print(cmdstr)
 94                     result = os.popen(cmdstr)
 95                     print(result.read())
 96                     self.request.send(result.read().encode('utf-8'))
 97         return
 98 
 99 with socketserver.TCPServer((host,port),MyFtpServerHandler) as ftpserver:
100     ftpserver.serve_forever()

 

posted @ 2017-11-15 15:25  susenyan  阅读(275)  评论(0编辑  收藏  举报