Python3实现简单的FTP认证服务器
时间: 2024-02-23 08:01:22 浏览: 23
好的,以下是一个简单的Python3实现FTP认证服务器的示例代码:
```python
import hashlib
import socket
import os
# 定义一个字典,存储已注册的用户信息,key为用户名,value为密码
users = {'user1': 'password1', 'user2': 'password2'}
# 定义一个哈希函数,用于将明文密码加密为哈希值
def hash_password(password):
return hashlib.sha256(password.encode()).hexdigest()
# 定义一个函数,用于验证用户是否合法
def authenticate_user(username, password):
if username not in users:
return False
return hash_password(password) == users[username]
# 创建一个TCP监听socket,接收客户端连接
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('0.0.0.0', 21))
server_socket.listen()
print('FTP server started, listening on port 21...')
while True:
# 接收客户端连接
client_socket, client_address = server_socket.accept()
print('New connection from', client_address)
# 发送欢迎信息
client_socket.send(b'220 Welcome to FTP server\r\n')
# 接收客户端发送的用户名和密码
username = ''
password = ''
while True:
data = client_socket.recv(1024).decode()
if not data:
break
print('Received:', data.strip())
if data.startswith('USER '):
username = data[5:].strip()
client_socket.send(b'331 Password required for ' + username.encode() + b'\r\n')
elif data.startswith('PASS '):
password = data[5:].strip()
if authenticate_user(username, password):
client_socket.send(b'230 Logged on\r\n')
break
else:
client_socket.send(b'530 Login incorrect\r\n')
# 如果用户验证通过,接收客户端发送的FTP命令
if username and password:
client_socket.send(b'220 FTP server ready\r\n')
while True:
data = client_socket.recv(1024).decode()
if not data:
break
print('Received:', data.strip())
if data.startswith('QUIT'):
client_socket.send(b'221 Goodbye\r\n')
break
elif data.startswith('PWD'):
current_dir = os.getcwd()
client_socket.send(('257 "%s"\r\n' % current_dir).encode())
elif data.startswith('CWD '):
path = data[4:].strip()
try:
os.chdir(path)
client_socket.send(('250 CWD command successful\r\n').encode())
except FileNotFoundError:
client_socket.send(('550 Directory not found\r\n').encode())
elif data.startswith('LIST'):
file_list = os.listdir('.')
response = ' '.join(file_list) + '\r\n'
client_socket.send(('150 Opening data connection\r\n').encode())
data_socket, _ = server_socket.accept()
data_socket.send(response.encode())
data_socket.close()
client_socket.send(('226 Transfer complete\r\n').encode())
else:
client_socket.send(('502 Command not implemented\r\n').encode())
# 关闭客户端socket
client_socket.close()
```
使用方法:
1. 将代码保存为ftp_server.py文件;
2. 在终端中运行命令python ftp_server.py,启动FTP服务器;
3. 使用FTP客户端连接到服务器,输入用户名和密码进行验证,然后执行FTP命令。
注意:此示例代码仅为演示使用,实际使用时应该加强安全性,例如使用SSL/TLS加密通信、限制IP地址访问、使用更强的密码哈希算法等。