第67天python学习基于tcp实例化实现远程执行命令

使用管道实现2个程序之间通信:例如:QQ  和微信通信

服务端:

from socket import *
import subprocess #管道模块,不同程序之间通信
ip_port="127.0.0.1",8080
back_log=5
buffer_size=1024

tcp_server=socket(AF_INET,SOCK_STREAM)
tcp_server.bind(ip_port)
tcp_server.listen(5)
while True:
conn,addr=tcp_server.accept()
print("新客户端链接",addr)
while True:
try:
cnd=conn.recv(buffer_size)
if not cnd :break
print("收到客户端的命令",cnd)

#执行命令得到运行cnd_res
res=subprocess.Popen(cnd.decode("utf-8"),shell=True, #把信息封装到管道里面
stderr=subprocess.PIPE, #把错误的信息搞到官道里面
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
err=res.stderr.read()
if err:
cnd_res=err
else:
cnd_res=res.stdout.read() ##把运行正确的信息从官道里面读出来

#把正确运行好的命令发给客户端
conn.send(cnd_res)
except Exception as e:
print(e)
break
conn.close()

客户端:

from socket import *
ip_port="127.0.0.1",8080
back_log=5
buffer_size=1024

tcp_clint=socket(AF_INET,SOCK_STREAM)
tcp_clint.connect(ip_port)
while True:
cnd=input(">>>:").strip()
if not cnd:continue #不能是空
if cnd=="quit":continue #按退出,允许退出
tcp_clint.send(cnd.encode("utf-8"))
cnd_res=tcp_clint.recv(buffer_size)
print("命令的执行结果是:",cnd_res.decode("gbk"))#服务器发送过来没有指定编码所有使用的是系统编码,Windows默认编码是gbk
tcp_clint.close()

猜你喜欢

转载自www.cnblogs.com/jianchixuexu/p/11875431.html