0

I want to interactive with subprocess terminal and send password, but I noticed that I could not get any stdout if some program call getpass(prompt)(http://www.gnu.org/savannah-checkouts/gnu/libc/manual/html_node/getpass.html)

That means I could not interactive with sudo and ssh, so how to solve this problem? Thanks.

Here is the example:

process = subprocess.Popen(['sudo', 'apt', 'update'],
                       bufsize=0,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       stdin=subprocess.PIPE)
while True:
    # prefix '>>' in parent process
    # but we could see the stdout without prefix, that means read() never return
    # the subprocess just ignored the redirect of stdout
    print('>>', process.stdout.read())
    time.sleep(1)
hfawja
  • 43
  • 6

1 Answers1

0

Your question is not clear, however i would try to answer

if you want to send password, you can use communicate() method

more information about communicate() is here Multiple inputs and outputs in python subprocess communicate

So your code would be like this

from subprocess import Popen,PIPE
proc = Popen(['sudo', 'apt', 'update'],
                       bufsize=0,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       stdin=subprocess.PIPE)

testoutput=proc.communicate(input='your password')[0] # This will enter the password and wait for the process to exit
print ''.join(testoutput)
pankaj mishra
  • 2,555
  • 2
  • 17
  • 31
  • Thank you for your answer, the code above is just an example.Running the code, we could see something in terminal without prefix, that means read() never return (the subprocess ignored the redirect of stdout). so I can't check sbuprocess' status. any advice? – hfawja Dec 27 '17 at 13:08
  • Have u used this code? U will able to see the output on screen..testoutput contains all the stdout and will be printed. – pankaj mishra Dec 27 '17 at 14:10
  • Well, I found the solution, also thank you for your reply, https://stackoverflow.com/questions/27933592/capturing-all-terminal-output-of-a-program-called-from-python – hfawja Dec 27 '17 at 14:12