Reputation: 4178
I have gone through multiple threads which has similar questions (Use subprocess to send a password) and have tried number of things but still i am not able to get it to work. Basically i want to push my ssh-keys to a bunch of machines and i am trying to do that with subprocess
. But somehow subprocess.Popen
fails to get the password and hence it gets stuck.
Below are some of things I have tried.
from subprocess import Popen, PIPE
p = Popen(['ssh-copy-id', 'testbox1'], stdin=PIPE, stdout=PIPE).communicate(input=b'mypassword')
I have also tried supplying the password by writing to process's stdin channel like below
p.stdin.write(b'mypassword')
p.stdin.flush()
I have tried this in both python 2.7 and python and it didn't work. I have also tried providing a linefeed as well after the password but even that didn't work. I am not sure what i am missing here.
I know people have suggested to use Pexpect
for this but then again i am more keen in knowing why subprocess
can't handle this.
I know there are multiple libraries like Paramiko
and also fabric
which handles remote connections with much ease, but i don't think that can be used in this case as i am not directly ssh
ing to a machine and rather using ssh-copy-id
command from my local machine
Upvotes: 1
Views: 703
Reputation: 4178
It seemed it was way to tricky to be handled with subprocess
and hence i had to pexpect
to solve this and it worked in first go.
import pexpect
from getpass import getpass
pwd = getpass("password: ")
child = pexpect.spawn('ssh-copy-id testbox1')
child.expect('.*ssword.*:')
child.sendline(pwd)
child.expect(pexpect.EOF, timeout=None)
cmd_show_data = child.before
cmd_output = cmd_show_data.split('\r\n')
for data in cmd_output:
print data
Upvotes: 1