向服务器发送空消息时Python客户端挂起

2021-12-01 11:38:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个python反向shell,它利用了使用TCP的客户机-服务器连接。我现在正在本地主机windows机器上测试它们,并利用子进程库处理命令。客户端应该向服务器发送一个命令,服务器将用输出返回

服务器:

import socket
import subprocess
import os

# Server

# creates TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# port and server ip(localhost)
LOCAL_HOST = '127.0.0.1'
PORT = 5565

BUFFER_SIZE = 5000  # size of message

no_char_message = "-1: Please enter a command"


# test connection
print("Server starting up on %s with port number %s" % (LOCAL_HOST, PORT))
# bind socket to ip and port
sock.bind((LOCAL_HOST, PORT))
# listen to socket
sock.listen(1)

# socket will accept connection and client address

print("Waiting for connection")  # waiting for connection
connection, address = sock.accept()  # accept connection with client address
print("Connected to", address)  # connected by address
while True:
    command = connection.recv(BUFFER_SIZE)  # receive message from client
    if not command:
        break
    if len(command) == 0:
        connection.send(str.encode(no_char_message))
    if len(command) > 0:
        terminal = subprocess.Popen(command[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE, stdin=subprocess.PIPE)
        output = terminal.stdout.read() + terminal.stderr.read()
        output_as_string = str(output, "utf-8")
        connection.send(str.encode(output_as_string))
        print(output_as_string)
print("Closing Server")
sock.close()
connection.close()

客户

import socket

# Client
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # creates TCP Socket

# local host and port
LOCAL_HOST = '127.0.0.1'

PORT = 5565
BUFFER_SIZE = 5000  # size of message

# connect socket to ip and port
sock.connect((LOCAL_HOST, PORT))
print("Connected to server\n")
while True:

    message = input("Please enter a command:\n")  # ask user to input message
    if message == 'quit':
        break
    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()

问题是,当我向服务器发送一条空消息时,它会挂起,只是说在终端中发送消息,而服务器从未收到任何消息。我不确定是什么原因造成的,但我假设管道堵塞,或者我没有正确处理

我希望服务器向客户机返回错误消息,而不是在客户机本身中处理错误消息

我尝试检查该命令的长度是否为0,并使用错误消息处理它,但它不起作用,仍然挂起

当我尝试使用date命令时,程序似乎也挂起了

通常,如果某个命令无法识别、为空或执行不成功,如何处理该条件