day26
基于TCP开发一款远程CMD程序
客户端连接服务器后,可以向服务器发送命令
服务器收到命令后执行,无论执行是否成功,无论执行几遍,都将执行结果返回给客户端
注意: 执行系统指令使用subprocess模块完成.
# sever
import socket
import subprocess
sever=socket.socket()
sever.bind(
('127.0.0.1',8001)
)
sever.listen(5)
while True:
conn,attr=sever.accept()
while True:
try:
date=conn.recv(1024).decode('gbk')
print('from client:', attr)
obj=subprocess.Popen(date,shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE)
stderr=obj.stderr.read()
stdout=obj.stdout.read()
conn.send(stderr)
conn.send(stdout)
except Exception as e:
print(e)
break
conn.close()
# client
import socket
client=socket.socket()
client.connect(
('127.0.0.1',8001)
)
while True:
send_msg=input('请输入你想要输入的命令:').strip()
client.send(send_msg.encode('gbk'))
if send_msg=='q':
break
date=client.recv(1024).decode('gbk')
print('from_server:',date)
client.close()