我遇到了 Pythons `subprocess.popen` 挂起的问题

I am having problems with Pythons `subprocess.popen` hanging

我有一个简单的函数,可以对列表中的多个项目调用相同的 subprocess.popen 命令。它执行列表中的前 2 项没有问题,但是第三项的操作挂起。

似乎 process_null.communicate() 从未执行或未完成至少因为我从未从列表中的第 3 项获得输出。我试过更改列表,但得到相同的结果。对这里发生的事情有什么想法吗?

def check_list(server_list):
    null_list = []

    for target in server_list:
        command_null="rpcclient -N -U '' {}". format (str(target))
        process_null = subprocess.Popen(command_null, shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        output_null = process_null.communicate()[0].replace('\n','')

        if "NT_STATUS_ACCESS_DENIED" in output_null or "NT_STATUS_CONNECTION_REFUSED" in output_null or "NT_STATUS_UNSUCCESSFUL" in output_null:
            print '[-]  ' + target + '\tDenied NULL Session'
        else:
            print '[+]  ' + target + '\tAccepted NULL Session'
            null_list.append(target)


    return null_list

输出

[-]  192.168.1.3    Denied NULL Session
[-]  192.168.1.65   Denied NULL Session

rpcclient 成功建立连接时,它会启动 shell 并等待在 stdin 上输入命令(如果 none 使用 -c 标志,这就是这里发生的事情。您没有看到提示,因为您将所有输出 (stdout + stderr) 重定向到管道,但您没有对 stdin 执行相同的操作,这意味着输入将是从 python 解释器 运行 开启的同一个 tty 读取。

此外,如果不是绝对必要,您不应将 shell=True 与字符串参数一起使用,而是使用参数列表:

command_null = ['rpcclient', '-N', '-U', '', str(target)]

要解决您的问题,您有两种选择:

  • 提供连接成功后要执行的命令:

    command_null = ['rpcclient', '-N', '-U', '', '-c', 'exit', str(target)]
    
  • 在打开进程时使用stdin=PIPE,这导致rcpclientstdincommunicate()关闭时退出:

    process_null = subprocess.Popen(command_null, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)