import socketserver
import os
def execCmd(cmd):
r = os.popen(cmd)
text = r.read()
r.close()
return text
# 自定义类来实现通信循环
class MyTCPHandler(socketserver.BaseRequestHandler):
# 必须写入handle方法,建立链接时会自动执行handle方法
def handle(self):
while True:
try:
data = self.request.recv(1024)
if not data: break
print('->client:', data)
#os.system(data.decode('utf-8'))
macd = execCmd(data.decode('utf-8'))
self.request.send(macd.encode('utf-8'))
except ConnectionResetError:
break
self.request.close()
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyTCPHandler)
server.serve_forever() # 链接循环