我有一个TCP客户端 - 服务器,其中客户端向服务器发送shell命令,服务器使用所述命令的输出进行响应。某些命令(如 date 或 cd)不起作用,因为它们是交互式的,我假设我的代码不处理它。每当我发送上述命令时,我的客户端似乎都挂起了,只是说发送...我的服务器从未收到任何东西。我想弄清楚如何处理这种情况,如果发送命令需要超过5秒的时间,客户端将导致超时,或者只是处理它并打印一条消息,指出命令未成功执行,同时保持客户端连接到服务器。这是我的代码客户:import socket# Clientsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # creates TCP Socket# local host and portLOCAL_HOST = '127.0.0.1'PORT = 5313BUFFER_SIZE = 5000 # size of messagesock.settimeout(5)# connect socket to ip and portsock.connect((LOCAL_HOST, PORT))print("Connected to server\n")print("Enter quit to close connection\n")while True: message = input("Please enter a command:\n") # ask user to input message if message == 'quit': break if len(message) == 0: print("Please enter something") message = input("Please enter a command:\n") print("Sending %s" % message) sock.send(str.encode(message)) # send message command = str(sock.recv(BUFFER_SIZE), "utf-8") # receive message print("received %s" % command)print("closing connection with server")sock.close()服务器:import socketimport subprocess# Server# Some commands do not work such as cd. Date does not work on windows because it is interactive.# creates TCP socketsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.settimeout(5)# port and server ip(localhost)LOCAL_HOST = ''PORT = 5313BUFFER_SIZE = 5000 # size of message# test connectionprint("Server starting up on %s with port number %s" % (LOCAL_HOST, PORT))# bind socket to ip and portsock.bind((LOCAL_HOST, PORT))# listen to socketsock.listen(1)
1 回答
繁星coding
TA贡献1797条经验 获得超4个赞
有多种方法可以做到这一点,但可能最简单的方法是调用subprocess.check_output()方法,该方法允许您以秒为单位指定超时值,并且还返回子进程生成的文本,即:
[...]
while True:
command = connection.recv(BUFFER_SIZE) # receive message from client
if not command:
break
command = command.decode("utf-8").strip()
if len(command) > 0:
try:
output_as_string = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True, timeout=5.0).decode("utf-8")
except subprocess.TimeoutExpired:
output_as_string = "Sub-process timed out!\r\n"
connection.send(str.encode("0:") + str.encode(output_as_string))
[...]
添加回答
举报
0/150
提交
取消