使用 SocketServer 实现 FTP Server

Posted pzk7788

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用 SocketServer 实现 FTP Server相关的知识,希望对你有一定的参考价值。

使用 SocketServer 实现 FTP Server ,以便让多个客户端进行上传下载

[[email protected] ~]# cat ftp_server.py
#!/usr/bin/env python
#!-*- coding:utf-8 -*-

import threading import SocketServer
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): while True: self.cmd = self.request.recv(1024).strip() self.cmd_list = self.cmd.split() if self.cmd_list: if self.cmd_list[0] == get: with open(self.cmd_list[1]) as fd: while True: self.data = fd.read(1024) self.request.sendall(self.data) if not self.data: self.request.sendall(EOF) break if not self.cmd: break class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass if __name__ == "__main__": HOST = "" PORT = 1234 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() print "Server loop running in thread:", server_thread.name server.serve_forever()
[[email protected] ~]# cat ftp_client.py
#!/usr/bin/env python
#!-*- coding:utf-8 -*-

import os import tab import time import socket HOST
= 192.168.1.16 PORT = 1234 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) while True: cmd = raw_input("Please input cmd: ").strip() if cmd.lower()== exit or cmd.lower() == quit: break cmd_list = cmd.split() if len(cmd_list) != 3: print "Ex: get file1 file2" continue else: s.sendall(cmd) if not os.path.exists(cmd_list[2]): dst_file = cmd_list[2] else: dst_file = cmd_list[2]+.new n = 1 while True: data_rev = s.recv(1024) if data_rev.endswith(EOF): data = data_rev[:-3] else: data = data_rev if n == 1: with open(dst_file, wb) as fd: fd.write(data) print data else: with open(dst_file, a) as fd: fd.write(data) print data n += 1 if data_rev[-3:] == EOF: print "destination file is %s" % dst_file break s.close()

 

 

 

 

 

 

 

     

以上是关于使用 SocketServer 实现 FTP Server的主要内容,如果未能解决你的问题,请参考以下文章

socketserver 模块实现ftp功能

Python-Socketserver实现FTP,文件上传下载

socketserver实现FTP

socketserver实现多用户同时在线ftp

python基础----socketserver多并发实现FTP上传多并发

python网络编程--socketserver 和 ftp功能简单说明