I\'m using subprocess to run a script from within python. I tried this
option 1
password = getpass.getpass()
from subprocess import Popen, PIPE, che
You should be passing the password as a value to the communicate()
function instead of stdin.write()
, like so:
from getpass import getpass
from subprocess import Popen, PIPE
password = getpass("Please enter your password: ")
proc = Popen("command option1 option2".split(), stdin=PIPE, stdout=PIPE)
# Popen only accepts byte-arrays so you must encode the string
proc.communicate(password.encode())
Here's a very basic example of how to use pexpect for this:
import sys
import pexpect
import getpass
password = getpass.getpass("Enter password:")
child = pexpect.spawn('ssh -l root 10.x.x.x "ls /"')
i = child.expect([pexpect.TIMEOUT, "password:"])
if i == 0:
print("Got unexpected output: %s %s" % (child.before, child.after))
sys.exit()
else:
child.sendline(password)
print(child.read())
Output:
Enter password:
bin
boot
dev
etc
export
home
initrd.img
initrd.img.old
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
selinux
srv
sys
tmp
usr
var
vmlinuz
vmlinuz.old
There are more detailed examples here.