服务器代码:
#-*- coding:utf-8 -*-
#edited by python3.6
#
import socket,os
'''
创建socket对象
'''
server = socket.socket()
'''
绑定ip和端口
'''
server.bind(('localhost',23233))
'''
监听端口
'''
server.listen()
while True:
conn,addr = server.accept()
print('======welcome to use leo\'s ssh========')
print('new connection:',addr)
while True:
print('等待新指令-->\r')
data = conn.recv(1024)
if not data:
print('客户端已断开!')
break
print('执行命令:',data)
cmd_result = os.popen(data.decode()).read() #接收来自客户端的数据
print('发送前的数据大小(byte):',len(cmd_result))
if len(cmd_result) == 0:
cmd_result = 'cmd has not output...'
conn.send(str(len(cmd_result.encode())).encode('utf-8'))
conn.send(cmd_result.encode('utf-8'))
print('发送完成。')
print('=========end==============\r')
'''
关闭程序
'''
server.close()
注:上述代码可能会造成粘包问题(即缓冲区将2行代码合并成一行执行),解决方式如下:
服务器:
conn.send(str(len(cmd_result.encode())).encode('utf-8'))
client_ack = conn.recv(1024)
conn.send(cmd_result.encode('utf-8'))
客户端:
print('命令执行结果大小为(byte):',cmd_result_size)
client.send('可以开始发送数据了!'.encode('utf-8'))
recv_size = 0
recv_data = b''
客户端代码:
#-*- coding:utf-8 -*-
#edited by python3.6
#
import socket
'''
创建socket对象
'''
client = socket.socket()
'''
连接到服务器
'''
client.connect(('localhost',23233))
while True:
cmd = input('[client]$ ').strip()
if len(cmd) == 0:continue
client.send(cmd.encode('utf-8'))
cmd_result_size = client.recv(1024)
print('命令执行结果大小为(byte):',cmd_result_size)
recv_size = 0
recv_data = b''
while recv_size < int(cmd_result_size.decode()):
data = client.recv(1024)
recv_size += len(data)
recv_data += data
else:
print('cmd result receive done...',recv_size)
print(recv_data.decode())
'''
关闭程序
'''
client.close()
及时行乐