FTP-实例(Md5验证)
import socket, os, hashlib server = socket.socket() server.bind(("localhost", 9999)) server.listen() while True: conn, addr = server.accept() print("new conn", addr) while True: print("等待新指令") data = conn.recv(1024) if not data: print("客户端已断开!") break cmd, filename = data.decode().split() print(filename) if os.path.isfile(filename): f = open(filename, "rb") m = hashlib.md5() file_size = os.stat(filename).st_size # 获取文件大小模块os.size conn.send(str(file_size).encode()) # send file size conn.recv(1024) # wait for ack for line in f: m.update(line) conn.send(line) print("file md5",m.hexdigest()) f.close() conn.send(m.hexdigest().encode())#发给客户端 print("send done") server.close()
上面是客户端FTP_server.py
import socket,hashlib client = socket.socket() client.connect(("localhost", 9999)) while True: cmd = input(">>:").strip() if len(cmd) == 0: continue if cmd.startswith("get"): client.send(cmd.encode()) server_response = client.recv(1024) print("server response:", server_response) client.send(b"ready to recv file") file_total_size = int(server_response.decode()) received_siez = 0 filename = cmd.split()[1] # 获取文件名字 f = open(filename + ".new", "wb") m =hashlib.md5() while received_siez < file_total_size: if file_total_size - received_siez >1024:#要收不止一次 size = 1024 else:#最后一次了,剩多少收多少 size =file_total_size - received_siez print("last receive",size) data = client.recv(size) received_siez += len(data) m.update(data) f.write(data) else: new_file_md5 = m.hexdigest() print("file recv done:",file_total_size, received_siez) f.close() server_file_md5= client.recv(1024) print("server file md5", server_file_md5) print("client file md5", new_file_md5) client.close()
上面是客户端FTP_client.py