Search code examples
python-3.xsubprocesspopen

Python3 Subprocess Popen send password to sudo and get result of process


I have a PyQt5 program where I get the users password for some PCI operations with a QInputDialog window. I can't seen to figure out how to get the output of the command that is ran by sudo.

john@d10shop:~/bin$ python3
Python 3.7.3 (default, Jan 22 2021, 20:04:44) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import Popen, PIPE
>>> password = 'xyz'
>>> p = Popen(['sudo', '-S', 'ls'], stdin=PIPE, stderr=PIPE, text=True)
>>> prompt = p.communicate(password + '\n')
camera  imap-1.py  pass.py
>>> prompt
(None, '[sudo] password for john: ')
>>> 

I can see the command is executed but I get the [sudo] password for john: but I need the output from ls in this example.

OS Debian 10

Thanks JT


Solution

  • From the python docs:

    Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

    You are missing the stdout=PIPE part to get the output. This works for me:

    p = Popen(['sudo', '-S', 'ls'], stdin=PIPE, stderr=PIPE, stdout=PIPE, text=True)
    prompt = p.communicate(password + '\n')
    output = prompt[0]