[英]Python subprocess hangs
我正在執行以下子流程...
p.call(["./hex2raw", "<", "exploit4.txt", "|", "./rtarget"])
...它掛了。
但是,如果我執行kmwe236@kmwe236:~/CS485/prog3/target26$ ./hex2raw < exploit4.txt | ./rtarget
kmwe236@kmwe236:~/CS485/prog3/target26$ ./hex2raw < exploit4.txt | ./rtarget
然后執行正常。 使用輸入或管道操作器有什么問題嗎?
我也嘗試了sp.call(["./hex2raw", "<", "exploit4.txt", "|", "./rtarget"], shell=True)
整個代碼看起來像這樣UPDATED SUGGESTIONS
import subprocess as sp
import pdb
for i in range(4201265,4201323):
pdb.set_trace()
d = hex(i)[2:]
output = " "
for i in range(len(d),0,-2):
output = output + d[i-2:i] + " "
out_buffer = "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00" + output + "00 00 00 00"
text_file = open("exploit4.txt", "w")
text_file.write("%s" % out_buffer)
# sp.call(["./hex2raw", "<", "exploit4.txt", "|", "./rtarget"], shell=True)
with open("exploit4.txt") as inhandle:
p = sp.Popen("./hex2raw",stdin=inhandle,stdout=sp.PIPE)
p2 = sp.Popen("./rtarget",stdin=p.stdout,stdout=sp.PIPE)
[output,error] = p2.communicate()
我遇到一個錯誤是
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 8] Exec format error
調試后,它發生在fire子p = sp.Popen("./hex2raw",stdin=inhandle,stdout=sp.PIPE)
調用p = sp.Popen("./hex2raw",stdin=inhandle,stdout=sp.PIPE)
由於您正在使用重定向和管道,因此必須啟用shell=True
sp.call(["./hex2raw", "<", "exploit4.txt", "|", "./rtarget"],shell=True)
但它是更清潔的使用Popen
兩個可執行文件和喂養的內容exploit4.txt
作為輸入。 下面的示例適合您的情況:
import subprocess
with open("exploit4.txt") as inhandle:
p = subprocess.Popen("./hex2raw",stdin=inhandle,stdout=subprocess.PIPE)
p2 = subprocess.Popen("./rtarget",stdin=p.stdout,stdout=subprocess.PIPE)
[output,error] = p2.communicate()
print(output)
# checking return codes is also a good idea
rc2 = p2.wait()
rc = p.wait()
說明:
inhandle
inhandle
,使用inhandle
將stdin
重定向,並將stdout
重定向到輸出流。 獲取管柄(p) stdin
與先前的進程stdout
重定向,並將stdout
重定向到輸出流 communicate
。 它將通過消耗其輸出來“拉”第一個:兩個進程都以管道方式工作 注意:因為一個或兩個可執行文件實際上是Shell或其他非本地可執行文件,所以會出現“格式錯誤”。 在這種情況下,只需將shell=True
選項添加到相關的Popen
調用中即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.