簡體   English   中英

Python子進程掛起

[英]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()

說明:

  1. 打開輸入文件,得到它的手柄inhandle
  2. 打開第一inhandle ,使用inhandlestdin重定向,並將stdout重定向到輸出流。 獲取管柄(p)
  3. 打開第二個子進程,將stdin與先前的進程stdout重定向,並將stdout重定向到輸出流
  4. 讓第二個進程進行communicate 它將通過消耗其輸出來“拉”第一個:兩個進程都以管道方式工作
  5. 獲取返回碼並打印結果

注意:因為一個或兩個可執行文件實際上是Shell或其他非本地可執行文件,所以會出現“格式錯誤”。 在這種情況下,只需將shell=True選項添加到相關的Popen調用中即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM