利用tcp协议实现远程控制

 远程控制服务端:

 1 from socket import *
 2 import subprocess
 3 
 4 tcp_server = socket(AF_INET, SOCK_STREAM)
 5 tcp_server.bind(('127.0.0.1', 8080))
 6 tcp_server.listen(128)
 7 while True:
 8     coon, addr = tcp_server.accept()
 9     print('新的客户端连接:', addr)
10     while True:
11         try:
12             cmd = coon.recv(1024)
13             res = subprocess.Popen(cmd.decode(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
14                                    stdin=subprocess.PIPE)
15             out = res.stdout.read()
16             err = res.stderr.read()
17             if out:
18                 coon.send(out)
19             elif err:
20                 coon.send(err)
21 
22         except Exception as f:
23             break
24 
25     coon.close()
26 tcp_server.close()

远程控制客户端代码:

 1 from socket import *
 2 
 3 tcp_client = socket(AF_INET, SOCK_STREAM)
 4 tcp_client.connect(('127.0.0.1', 8080))
 5 while True:
 6     cmd = input('请输入指令:').strip()
 7     if not cmd: continue
 8     if cmd == 'quit': break
 9     tcp_client.send(cmd.encode())
10     data = tcp_client.recv(1024)
11     print(data.decode('GBK'))

 

上一篇:python自动安装缺少依赖项


下一篇:Python subprocess