python ftp服务器搭建_利用Python快速搭建HTTP&FTP服务器
时间: 2024-05-10 07:16:36 浏览: 184
Python自带了一个ftplib模块,可以用来创建FTP服务器。下面是一个简单的Python脚本,用于创建一个FTP服务器:
```python
import os
import sys
from ftplib import FTP
from threading import Thread
class FTPHandler(FTP):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.cwd = os.getcwd()
def cdup(self):
self.cwd = os.path.dirname(self.cwd)
super().cwd(self.cwd)
def cwd(self, path):
self.cwd = os.path.join(self.cwd, path)
super().cwd(self.cwd)
def handle_client(client_socket):
"""
处理客户端请求
"""
ftp = FTPHandler()
ftp.set_pasv(True)
ftp.sock = client_socket
print('FTP连接来自:', client_socket.getpeername())
ftp.welcome = 'Welcome to my FTP server.'
ftp.login()
while True:
try:
cmd = client_socket.recv(1024).decode()
if not cmd:
break
print(cmd)
cmd = cmd.split()
if cmd[0] == 'QUIT':
ftp.quit()
break
elif cmd[0] == 'CWD':
ftp.cwd(cmd[1])
client_socket.send(b'250 Directory changed.\r\n')
elif cmd[0] == 'CDUP':
ftp.cdup()
client_socket.send(b'200 Directory changed.\r\n')
elif cmd[0] == 'PWD':
client_socket.send(('257 "%s"\r\n' % ftp.cwd).encode())
elif cmd[0] == 'LIST':
data_socket, addr = ftp.transfercmd('LIST')
client_socket.send(b'150 Here comes the directory listing.\r\n')
data = data_socket.recv(1024)
while data:
client_socket.send(data)
data = data_socket.recv(1024)
data_socket.close()
client_socket.send(b'226 Directory send OK.\r\n')
elif cmd[0] == 'RETR':
file = open(os.path.join(ftp.cwd, cmd[1]), 'rb')
data_socket, addr = ftp.transfercmd('RETR ' + cmd[1])
client_socket.send(b'150 Opening data connection.\r\n')
data = file.read(1024)
while data:
data_socket.send(data)
data = file.read(1024)
file.close()
data_socket.close()
client_socket.send(b'226 Transfer complete.\r\n')
else:
client_socket.send(('502 Command not implemented.\r\n').encode())
except Exception as e:
print(e)
break
client_socket.close()
def main():
"""
启动服务器
"""
host = ''
port = 21
backlog = 5
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(backlog)
print('FTP服务器已经启动,监听端口为:', port)
while True:
try:
client_socket, addr = server_socket.accept()
Thread(target=handle_client, args=(client_socket,)).start()
except KeyboardInterrupt:
sys.exit(0)
if __name__ == '__main__':
main()
```
该脚本启动一个FTP服务器,监听21端口。在客户端输入命令时,它会响应CWD、CDUP、PWD、LIST和RETR命令。
使用该脚本非常简单,只需要运行该脚本即可启动一个FTP服务器。
阅读全文