复习

复习用tcp协议进行远程运行终端。

服务端代码:

 1 from socket import *
 2 import struct
 3 import subprocess
 4 tcp_server = socket(AF_INET,SOCK_STREAM)
 5 tcp_server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
 6 tcp_server.bind(('127.0.0.1',8080))
 7 tcp_server.listen(124)
 8 while True:
 9     coon,addr = tcp_server.accept()
10     while True:
11         cmd = coon.recv(1024)
12         cmd_res = subprocess.Popen(cmd.decode(),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
13         err = cmd_res.stderr.read()
14         if err:
15             send_res = err
16         else:
17             send_res = cmd_res.stdout.read()
18         length = len(send_res)
19         coon.send(struct.pack('i',length))
20         coon.send(send_res)
21         # ready = coon.recv(1024)
22         # if ready == b'ready':
23         #     coon.send(send_res)

客户端:

 1 from socket import *
 2 import struct
 3 
 4 tcp_client = socket(AF_INET, SOCK_STREAM)
 5 tcp_client.connect(('127.0.0.1', 8080))
 6 while True:
 7     cmd = input('请输入指令:')
 8     tcp_client.send(cmd.encode())
 9     length = tcp_client.recv(4)
10     length = struct.unpack('i', length)[0]
11     recv_length = 0
12     data = b''
13     while recv_length < length:
14         data += tcp_client.recv(100)
15         recv_length = len(data)
16     print(data.decode('gbk'))

 

上一篇:socket网络编程学习


下一篇:Go之获取系统性能指标 - goPsutil