socket远程执行命令
两个脚本模拟远程执行命令
cmd_server.py
import socket import subprocess # 运行系统命令 sk = socket.socket() addess = ('127.0.0.1', 8000) sk.bind(addess) sk.listen(3) conn, addr = sk.accept() print('有客户端连接:', addr) data = conn.recv(1024) # 接收客户端的系统命令 obj = subprocess.Popen(str(data, 'utf8'),shell=True,stdout=subprocess,PIPE) # 系统命令的运行结果 cmd_result = obj.stdot.read() # 默认以'gbk'编码
len_result = bytes(str(len(cmd_result))'utf8') # 计算字节数
conn.send(len_result) # 发送字节数
conn.send(cmd_result) # 发送
cmd_client.py
import socket sk =socket.socket() addess = ('127.0.0.1', 8000) sk.connect(addess) while True: inp = input('>>:') sk.send(bytes(inp, 'utf8')) # 发送系统命令,
data = sk.recv(1024)
len_result = int(str(data, 'utf8')) # 字节数
data = bytes()
while len(data) != len_result:
recv = sk.recv(1024)
data += recv
print(str(data, 'gbk')) # 以'gbk'解码