三次握手、四次挥手图示意图
基于TCP开发一款远程cmd程序
# server.py
import socket
import subprocess
server = socket.socket()
# 设置服务端IP和端口
server.bind(
('127.0.0.1', 8888)
)
# 半连接池
server.listen(5)
while True:
# 等待客户端连接
conn, addr = server.accept()
print(addr)
while True:
try:
# 接收客户端数据
cmd = conn.recv(1024).decode('gbk')
print(cmd)
res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 成功执行指令后返回的结果
output = res.stdout.read()
# 终端报错结果
error = res.stderr.read()
# 向客户端发送数据
if output:
conn.send(output)
if error:
conn.send(error)
except Exception as e:
print(e)
break
conn.close()
# client.py
import socket
client = socket.socket()
# 连接服务端
client.connect(
('127.0.0.1', 8888)
)
while True:
cmd = input('请输入指令: ').strip()
if cmd == 'q':
break
# 向服务端发送数据
client.send(cmd.encode('gbk'))
# 接收服务端数据
res = client.recv(1024)
print(res.decode('gbk'))
# 关闭连接
client.close()