远程操控:客户端输入一个命令ipconfig 通过网络传输 传输给服务器,服务器后端运行此命令得到一个结果
将结果再通过网络传输返回给客户
import subprocess
obj=subprocess.Popen('dir',
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
print(obj.stdout.read().decode('gbk'))
print(obj.stderr.read().decode('gbk'))
shell:命令解释器,相当于调用cmd执行指定的命令
stdout:正确结果丢到管道中
stderr:错的丢到另一个管道中
windows操作系统的默认编码是gbk编码
远程操控命令:
服务端:
import socket
import subprocess
server=socket.socket()
server.bind(('127.0.0.1',3333))
server.listen(5)
while 1:
conn,addr=server.accept()
while 1:
try:
cmd=conn.recv(1024).decode('utf-8')
obj=subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
right_msg=obj.stdout.read()
error_msg=obj.stderr.read()
print(right_msg,error_msg)
conn.send(right_msg+error_msg)
except Exception:
break
conn.close()
server.close()
客户端:
import socket
client=socket.socket()
client.connect(('127.0.0.1',3333))
while 1:
cmd=input('>>>').strip()
client.send(cmd.encode('utf-8'))
from_server_cmd=client.recv(1024)
print(from_server_cmd.decode('gbk'))
client.close()