import subprocess
password= "xyz"
p = subprocess.Popen(["sudo", "-S", "whoami"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
print (p.communicate((password+"\n").encode()))
ps = subprocess.Popen(["sftp", "user@sftphost"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
print (ps.communicate((password+"\n").encode())) # without print as well I get prompted for password
First command (sudo -S whoami
) is successful through subprocess
taking the password correctly. However, the password is not accepted for sftp
command – I am still getting prompted to enter password.
I have the same question as Use subprocess to send a password. However, I do not want to use the solution like Pexpect or expect
. I have tried rest of the solutions.
Want to know why this fails for sftp
and is there any other way?
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.