Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subprocess + scp - can't read all output

I'm trying to SCP a file between machines and I need to fail when the user hasn't set up a private/public certificate to do passwordless logins. Unfortunatly, using subprocess.Popen I can't figure out how to capture the following output:

The authenticity of host '***' can't be established.
RSA key fingerprint is ***.
Are you sure you want to continue connecting (yes/no)

It always shows up on the console and I can't get it in my program to detect it.

Here's some example code:

proc = subprocess.Popen(['scp', 'user@server:/location/file.txt', '/someplace/file.txt',
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
proc.wait()
print 'result: %s' % repr(proc.stderr.readline())

I've tried many other permutations. This one still prompts me, and not Python to enter yes/no. At least when I type no though I get:

result: 'Host key verification failed.\r\n'
like image 504
sudoer Avatar asked Apr 18 '26 02:04

sudoer


1 Answers

'The authenticity of host '***' can't be established' means the machine your connecting from hasn't been told to save the other ends (server) identity to the known_hosts file and it asking if you trust the machine. You can change the ssh client to just add it automatically without prompting you.

try this:

proc = subprocess.Popen(['scp', '-o BatchMode=yes',
                                'user@server:/location/file.txt',
                                '/someplace/file.txt'],
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
proc.wait()
print 'result: %s' % repr(proc.stderr.readline())

With the above code i get:

me@myMachine:~$ python tmp.py 
result: 'Host key verification failed.\r\n'
me@myMachine:~$

If I use disable StrictHostKeyChecking i get:

me@myMachine:~$ python tmp.py
result: 'Permission denied (publickey,password,keyboard-interactive).\r\n'
me@myMachine:~$ python tmp.py

So it looks like it is printing the first line from stderr with BatchMode turned on :)

like image 175
tMC Avatar answered Apr 20 '26 15:04

tMC