How to redirect data to "getpass", for example, to enter a password?

I am running a python script to run some command. Some of these commands require the user to enter a password, I tried to enter data into their stdin, but it does not work, here are two simple python programs that present a 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 conclusion

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

It just stops at pass1 field. Here is the problem, why can not I put the data in stdin to transfer data in the password field? How can I write the data in the password fields?

+4
source share
2 answers

For such cases, you need the pexpect module.

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

+2
source

There is definitely no need for two classes to do something like this. All you have to do is create another method in put_data.py called init _ () and then do something according to the lines:

 x = raw_input('text1:') y = getpass.getpass('pass1:') z = getpass.getpass('pass2:') 

Then you can just use pexpect for the rest:

 child = pexpect.spawn(x, timeout=180) while True: x = child.expect(["(current)", "new", "changed", pexpect.EOF, pexpect.TIMEOUT]) if x is 0: child.sendline(y) time.sleep(1) if x is 1: child.sendline(z) time.sleep(1) if x is 2: print "success!" break 

TA-dah! Of course, you are likely to get a ton of errors with such code. You should always use the provided methods, if you are using linux, it is easier to run os.system ("passwd") and let the shell take care of the rest. Also, if at all possible, always avoid using getpass, it is a funky outdated method and can damage things along the way.

0
source

Source: https://habr.com/ru/post/1337446/


All Articles