I have problems using the subprocess module to obtain the output of crashed programs. I'm using python2.7 and subprocess to call a program with strange arguments in order to get some segfaults In order to call the program, I use the following code:
proc = (subprocess.Popen(called,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE))
out,err=proc.communicate()
print out,err
called is a list containing the name of the program and the argument (a string containing random bytes except the NULL byte which subprocess doesn't like at all)
The code behave and show me the stdout and stderr when the program doesn't crash, but when it does crash, out and err are empty instead of showing the famous "Segmentation fault".
I wish to find a way to obtain out and err even when the program crash.
I also tried the check_output / call / check_call methods
Some additional information:
I'm running this script on an Archlinux 64 bits in a python virtual environment (shouldn't be something important here, but you never know :p)
The segfault happens in the C program I'm trying to run and is a consequence of a buffer overflow
The problem is that when the segfault occurs, I can't get the output of what happened with subprocess
I get the returncode right: -11 (SIGSEGV)
Using python i get:
./dumb2 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
('Exit code was:', -11)
('Output was:', '')
('Errors were:', '')
While outside python I get:
./dumb2 $(perl -e "print 'A'x50")
BEGINNING OF PROGRAM
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
END OF THE PROGRAM
Segmentation fault (core dumped)
The return value of the shell is the same: echo $? returns 139 so -11 ($? & 128)
Came back here: it works like a charm with subprocess from python3 and if you are on linux, there is a backport to python2 called subprocess32
which does work quite well
Older solution: I used pexpect and it works
def cmd_line_call(name, args):
child = pexpect.spawn(name, args)
# Wait for the end of the output
child.expect(pexpect.EOF)
out = child.before # we get all the data before the EOF (stderr and stdout)
child.close() # that will set the return code for us
# signalstatus and existstatus read as the same (for my purpose only)
if child.exitstatus is None:
returncode = child.signalstatus
else:
returncode = child.exitstatus
return (out, returncode)
PS: a little slower (because it spawns a pseudo tty)