Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect data to a "getpass" like password input?

I'm wring a python script for running some command. Some of those commands require user to input password, I did try to input data in their stdin, but it doesn't work, here is two simple python program represent the problem

input.py

import getpass

print raw_input('text1:')
print getpass.getpass('pass1:')
print getpass.getpass('pass2:')

put_data.py

import subprocess
import getpass

def run(cmd, input=None):
    stdin=None
    if input:
        stdin=subprocess.PIPE
    p = subprocess.Popen(cmd, shell=True, stdin=stdin)
    p.communicate(input)
    if p.returncode:
        raise Exception('Failed to run command %r' % cmd)

input ="""text1
password1
password2
"""
run('python test.py', input)

And here is the output

[guest@host01 ~]# python put_data.py 
text1:text1
pass1:

It just stop there on the pass1 field. Here is the problem, why I can't put data to stdin to feed data to the password field? How can I write data to password fields?

like image 261
Fang-Pen Lin Avatar asked Jan 28 '11 09:01

Fang-Pen Lin


1 Answers

You need the pexpect module for such cases.

Pexpect is a Python module for spawning child applications and controlling them automatically. Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc.

like image 135
user225312 Avatar answered Oct 02 '22 16:10

user225312