基于tcp实现远程执行命令

命令执行服务器:

 1 # Author : Kelvin
 2 # Date : 2019/1/30 20:10
 3 from socket import *
 4 import subprocess
 5 
 6 ip_conf = ("127.0.0.1", 8888)
 7 buffer_capacity = 1024
 8 tcp_server = socket(AF_INET, SOCK_STREAM)
 9 tcp_server.bind(ip_conf)
10 tcp_server.listen(5)
11 while True:
12     conn, addr = tcp_server.accept()
13     while True:
14         try:
15             cmd = conn.recv(buffer_capacity) #如果强制断开连接会触发try,try正是解决强制中断连接的问题
16             print("收到的cmd:%s"%cmd)
17             if not cmd: #如果使用quit断开连接,服务器会死循环收到空,该判断正是解决此问题
18                 break
19             res = subprocess.Popen(cmd.decode("utf8"), shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
20                                    stderr=subprocess.PIPE)
21             err = res.stderr.read()
22             if err:
23                 back_msg = err
24             else:
25                 back_msg = res.stdout.read()
26             conn.send(back_msg)
27         except Exception as e:
28             print(e)
29             break
30 tcp_server.close()

客户端:

 1 # Author : Kelvin
 2 # Date : 2019/1/30 20:10
 3 from socket import *
 4 
 5 ip_conf = ("127.0.0.1", 8888)
 6 buffer_capacity = 1024
 7 tcp_client = socket(AF_INET, SOCK_STREAM)
 8 tcp_client.connect(ip_conf)
 9 while True:
10     cmd = input("Please input cmd : ")
11     if not cmd:
12         continue
13     if cmd == "quit":
14         break
15     tcp_client.send(cmd.encode("utf8"))
16     back_msg = tcp_client.recv(buffer_capacity).decode("gbk")
17     print(back_msg)
18 tcp_client.close()

执行结果:

原文地址:https://www.cnblogs.com/sun-10387834/p/10339756.html