系统相关
首页 > 系统相关> > python – 捕获崩溃的子进程的“分段错误”消息:在调用communication()之后没有输出和错误

python – 捕获崩溃的子进程的“分段错误”消息:在调用communication()之后没有输出和错误

作者:互联网

我在使用子进程模块获取崩溃程序的输出时遇到问题.
我正在使用python2.7和subprocess来调用带有奇怪参数的程序,以获得一些段错误
为了调用程序,我使用以下代码:

proc = (subprocess.Popen(called,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE))
out,err=proc.communicate()
print out,err

called是一个包含程序名称和参数的列表(包含随机字节的字符串,除了子进程完全不喜欢的NULL字节)

当程序没有崩溃时代码表现并向我显示stdout和stderr,但是当它崩溃时,out和err是空的而不是显示着名的“Segmentation fault”.

即使程序崩溃,我希望找到一种方法来获取和错误.

希望有人在这里作为一个想法:)

PS:我也尝试过check_output / call / check_call方法

编辑:

>我在一个python虚拟环境中的Archlinux 64位上运行这个脚本(这里不应该是重要的东西,但你永远不会知道:p)
>段错误发生在我正在尝试运行的C程序中,是缓冲区溢出的结果
>问题是当发生段错误时,我无法获得子进程发生的输出
>我得到了正确的返回码:-11(SIGSEGV)
>使用python我得到:

 ./dumb2 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 
 ('Exit code was:', -11) 
 ('Output was:', '') 
 ('Errors were:', '')

>在python之外,我得到:

./dumb2 $(perl -e "print 'A'x50")  
BEGINNING OF PROGRAM 
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
END OF THE PROGRAM
Segmentation fault (core dumped)

> shell的返回值是相同的:echo $?返回139所以-11($?& 128)

解决方法:

shell可能会生成“Segmentation fault”消息.要找出该过程是否被SIGSEGV杀死,请检查proc.returncode == -signal.SIGSEGV.

如果要查看消息,可以在shell中运行该命令:

#!/usr/bin/env python
from subprocess import Popen, PIPE

proc = Popen(shell_command, shell=True, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
print out, err, proc.returncode

我已经用ctypes import *; memset(0,1,1)’中的shell_command =“python -c”测试了它,导致了段错误并且错误捕获了消息.

如果消息直接打印到终端,那么您可以使用pexpect模块捕获它:

#!/usr/bin/env python
from pipes import quote
from pexpect import run # $pip install pexpect

out, returncode = run("sh -c " + quote(shell_command), withexitstatus=1)
signal = returncode - 128 # 128+n
print out, signal

或直接使用pty stdlib模块:

#!/usr/bin/env python
import os
import pty
from select import select
from subprocess import Popen, STDOUT

# use pseudo-tty to capture output printed directly to the terminal
master_fd, slave_fd = pty.openpty()
p = Popen(shell_command, shell=True, stdin=slave_fd, stdout=slave_fd,
          stderr=STDOUT, close_fds=True)
buf = []
while True:
    if select([master_fd], [], [], 0.04)[0]: # has something to read
        data = os.read(master_fd, 1 << 20)
        if data:
            buf.append(data)
        else: # EOF
            break
    elif p.poll() is not None: # process is done
        assert not select([master_fd], [], [], 0)[0] # nothing to read
        break
os.close(slave_fd)
os.close(master_fd)
print "".join(buf), p.returncode-128

标签:fuzzing,python,segmentation-fault,subprocess,communicate
来源: https://codeday.me/bug/20190919/1812441.html