client端执行命令,server端返回命令结果
# server 端
import socket, subprocess
sk = socket.socket()
address=('127.0.0.1', 8000)
sk.bind(address)
sk.listen(3)
print('waiting....')
while 1:
conn, addr = sk.accept()
print(addr)
while 1:
try:
data = conn.recv(1024)
except Exception:
break
if not data: break
print('.........', str(data, 'utf8'))
obj = subprocess.Popen(data.decode('utf8'), shell=True, stdout=subprocess.PIPE)
cmd_result = obj.stdout.read()
result_len = bytes(str(len(cmd_result)), 'utf8')
print('>>>>>>', result_len)
conn.sendall(result_len)
conn.recv(1024) # 预防粘包现象
conn.sendall(cmd_result)
sk.close()
# client 端
import socket
sk = socket.socket()
print(sk)
address = ('127.0.0.1', 8000)
sk.connect(address)
while True:
inp = input('>>>')
if inp == 'exit':
break
sk.send(bytes(inp, 'utf8'))
result_len = int(str(sk.recv(1024), 'utf8'))
sk.sendall(bytes('ok', 'utf8'))
print(result_len)
data = bytes()
while len(data) != result_len:
recv = sk.recv(1024)
data += recv
print(str(data, 'gbk'))
sk.close()