Use Subprocess to Send a Password

Use subprocess to send a password

Perhaps you should use an expect-like library instead?

For instance Pexpect (example). There are other, similar python libraries as well.

unable to provide password to a process with subprocess [python]

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.

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

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]

Send password to sftp subprocess in Python

OpenSSH sftp always reads the password from the terminal (it does not have an equivalent of sudo -S switch).

There does not seem to be a readily available way to emulate a terminal with subprocess.Popen, see:
How to call an ncurses based application using subprocess module in PyCharm IDE?


You can use all the hacks that are commonly used to automate password authentication with OpenSSH sftp, like sshpass or Expect:

How to run the sftp command with a password from Bash script?

Or use a public key authentication.


Though even better is to use a native Python SFTP module like Paramiko or pysftp.

With them, you won't have these kinds of problems.

Sending a password over SSH or SCP with subprocess.Popen

The second answer you linked suggests you use Pexpect(which is usually the right way to go about interacting with command line programs that expect input). There is a fork of it which works for python3 which you can use.

How do I enter a password after subprocess.call()

I found that using:

echo password

works and there errors can be ignored. The reason why I thought it was terminating before completion was because the file size was so small. After running it manually in the terminal for the same date range the file sizes match and it was due to the small amount of data available for that date range.



Related Topics



Leave a reply



Submit