1017 作业
1.画图整理
三次握手建立连接
四次挥手断连接
2.基于TCP开发一款远程CMD程序
客户端连接服务器后,可以向服务器发送命令
服务器收到命令后执行,无论执行是否成功,无论执行几遍,都将执行结果返回给客户端
注意: 执行系统指令使用subprocess模块完成.
# server.py
import socket
import subprocess
server = socket.socket()
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('utf-8')
print('来自客户端的命令:', cmd)
if len(cmd) == 0:
continue
if cmd == 'q':
break
res = subprocess.Popen(cmd, shell=True,
stderr=subprocess.PIPE,
#stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
data1 = res.stdout.read()
data2 = res.stderr.read()
conn.send(data1 + data2)
print('客户端中内容为:\n', (data1+data2).decode('gbk'))
except Exception as e:
print(e)
break
conn.close()
# client
import socket
client = socket.socket()
client.connect(
('127.0.0.1', 8888)
)
while True:
cmd = input('输入命令:')
client.send(cmd.encode('utf-8'))
if cmd== 'q':
break
data = client.recv(1024).decode('gbk')
print(data)
client.close()