Search code examples
pythonpython-2.7ubuntuubuntu-16.04sudo

python: subprocess gives me different results while using sudo


I'm using python to do some tests and I get a very weird issue as below:

First I have a simple bash script named 1.sh:

#!/bin/sh

echo 'NOTHING'

Then I make such a python script named test.py in the same directory as below:

#!/usr/bin/python

import subprocess
import os

os.environ['PS4'] = "aaa "
res=subprocess.Popen(['bash', '-x', '1.sh'], stderr = subprocess.PIPE)
print res.stderr.readlines()

To my surprise, when I execute ./test.py, I get the result:

NOTHING
['aaa echo NOTHING\n']

and when I execute sudo ./test.py, I get:

NOTHING
['+ echo NOTHING\n']

What I need is aaa whereas it becomes a + now just because of sudo.

Why?

The version of my python: 2.7.12
The system: ubuntu 16.04


Solution

  • It appears there has been a bug in bash, allowing arbitrary code injection through inherited PS4 variable in root shell. https://bugzilla.redhat.com/show_bug.cgi?id=1379630

    The bug has been fixed, and it appears PS4 is completely ignored if bash is run as root. You can test this:

    sudo bash
    export PS4="xyzzy "
    bash -x 1.sh
    

    and notice you still get +. No matter what you set in PS4, it seems to be never displayed if your uid is zero. This of course is not a solution, but if this is true, what you want to do cannot be done with PS4.

    As a workaround I suggest reading res.stderr line by line and running a regexp based substitution replacing ^+ with your chosen prompt.