python - 杀死由python脚本执行的C程序

标签 python c

我目前正在使用 python 脚本来运行类似 c 的可执行文件

os.system("./a.out \"%s\" " %p)

我可以使用许多二进制指令(i1、i2、i3 .... 确切地说是 i10)。我在 python 中使用 itertools 生成这些指令(长度为 1、2、3...10)的排列。字符串 payload p(在上面的代码片段中)就是这样一种排列。我正在测量每个排列所花费的时间,如下所示:

start = time.clock()
os.system("./a.out \"%s\" " %p)
print time.clock() - start

(这可能不是衡量时间的最佳方式。但这是另一个问题的主题。)
现在对于一些排列我得到段错误并且 python 脚本继续进行另一个排列。但是对于某些排列,我没有得到任何响应(就像陷入无限循环),例如:

58 60 452 547 583 649 756 777 932 965 
key  Not found
(Nothing happens after this. This is due to bad combination 
 of instructions or bad payload.
I have to press ctrl C to proceed to next permutation)
^C---------------[9 8 ]------------
The gadget seq is [mov,ret xor eax,eax,ret ] and time taken is 
0.000254 (this is the bad permutation of instructions)

(Next permutation.. )

在我按下 Ctrl + C 后,python 脚本进入下一个排列。说得更清楚

perm = itertools.permutations(gadget_list,2) #perm is list of all permutations of 2 instructions
for string in list(perm):
#generate the payload p from string which is one of the permutation
#feed it to c program and measure time
    start = time.clock()
    os.system("./a.out \"%s\" " %p)
    print time.clock() - start

现在对于更长的排列长度,对每个错误的有效载荷按 Ctrl C 变得很乏味。有什么方法可以自动终止/停止 C 程序(我是通过按 Ctrl C 来执行的),该程序因有效负载错误而卡住并继续进行下一个排列?

最佳答案

要获得对子进程的更多控制,您需要使用subprocess 模块。

import time
from subprocess import Popen
from shlex import split

proc = Popen(split("./a.out '%s'" % p))

rtime, timeout = 0, 10
while rtime < timeout:
    rc = proc.poll()
    if rc is not None:
       break # process finished.
    time.sleep(1)
    rtime += 1
else:
    proc.kill()

关于python - 杀死由python脚本执行的C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40459356/

相关文章:

Python 创建供本地使用的包

我们能否始终针对崩溃问题获得正确(或完整)的堆栈转储

c - CUDD 的 bool 表达式解析器

c++ - 更改代码块中的链接器顺序

c - 电位计作为 MSP430g2452 启动板的输入

python - Python中与组相关的常量

python - 在 Windows 上使用 Python 连接 gzipped 文件

Python httplib.HTTPS连接和密码

python - Pandas :按列分组,将列表行合并为组的单个列?

c - 如何检查bool是否已经存在