ssh服务端
import socket,os server = socket.socket() server.bind((‘localhost‘,6666)) server.listen() conn, addr = server.accept() while True: print(‘等待新数据!‘) cmd = conn.recv(1024) if len(cmd) == 0: break data = os.popen(cmd.decode()).read() cmd_size = len(data.encode(‘utf-8‘)) print(‘检测到数据大小‘,cmd_size) if len(data) == 0: data = ‘没有此命令!!‘ conn.send(str(len(data.encode(‘utf-8‘))).encode()) order = conn.recv(1024) conn.send(data.encode(‘utf-8‘)) print(‘传送完成!‘) server.close()
ssh客户端
import socket client = socket.socket() client.connect((‘localhost‘,6666)) while True: cmd = input(‘>>>:‘) if cmd == 0: continue client.send(cmd.encode(‘utf-8‘)) cmd_size = client.recv(1024) print(‘服务端检测到数据大小:‘, cmd_size) if len(cmd_size) !=0: client.send(‘可以发送数据了‘.encode(encoding=‘utf-8‘)) receive_size = 0 receive_cmd = b‘‘ while receive_size < int(cmd_size.decode()): data = client.recv(1024) receive_size += len(data) receive_cmd += data else: print(‘接收到数据大小:‘,receive_size) print(‘数据接收完成!‘) print(receive_cmd.decode())
socket文件传输并校验
服务端
import socket,os,hashlib server = socket.socket() server.bind((‘localhost‘,6666)) server.listen() conn, addr = server.accept() while True: print(‘等待新数据!‘) cmd = conn.recv(1024) if len(cmd) == 0: break filename = cmd.decode().split()[1] print(filename) if os.path.isfile(filename): #判断文件是否存在 f = open(filename,‘rb‘) #打开文件 m = hashlib.md5() file_size = os.stat(filename).st_size #查询文件大小 print(file_size) conn.send(str(file_size).encode()) #给客户端发送文件大小 conn.recv(1024) #等待并接受客户端的确认,这一步可以解决粘包问题 for line in f: #边读边循环发送文件 m.update(line) #得出每一句的md5值 conn.send(line) #发送给客户端 print(‘file md5:‘,m.hexdigest()) f.close() conn.recv(1024) conn.send(m.hexdigest().encode()) print(‘传送完成!‘) server.close()
socket文件传输并校验
客户端
import socket,hashlib client = socket.socket() client.connect((‘localhost‘,6666)) while True: cmd = input(‘>>>:‘).strip() if len(cmd) == 0: continue if cmd.startswith(‘get‘): #传输文件名要以get开头如:get var client.send(cmd.encode(‘utf-8‘)) file_size = client.recv(1024) print(‘服务端检测到文件大小:‘, int(file_size)) client.send(‘可以发送数据了‘.encode(encoding=‘utf-8‘)) file_total_size = int(file_size) receive_size = 0 filename = cmd.split()[1] #以空格分割然后取出文件名 f = open(‘new_‘+filename ,‘wb‘) m = hashlib.md5() while receive_size < file_total_size: data = client.recv(1024) m.update(data) receive_size += len(data) f.write(data) print(file_total_size, receive_size) else: new_file_md5 = m.hexdigest() print(‘数据接收完成!‘) f.close() client.send(‘可以发送md5值了‘.encode()) serve_md5 = client.recv(1024) print(‘新文件md5:‘,new_file_md5) print(‘原文件md5:‘,serve_md5) client.close()
原文地址:https://www.cnblogs.com/hsj-jingyu/p/8439900.html
时间: 2024-11-05 21:57:03