Python Forum

Full Version: Pexpect not catching embeded ssh response
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everybody,
I was used to Bash + TCL + Expect but I migrated to Python + Pexpect and I'm encountering a little problem. I'm running python 3.6 with pexpect 4 in an ubuntu minimal vm. I'm spawning a child process to a proxy ssh machine and then trying to ssh again other hosts (this is in the aim of testing accesibility + accounts configurated after some network changes we hve to do). Problem is that pexpect library won't catch the second password prompt. I can login to the proxy ssh server but I can't "jump" to other machines. This is my script:

from __future__ import unicode_literals
import pexpect
import getpass

#username = input('Please enter your username:')
username = 'XXX'
password = getpass.getpass('Please enter your Password:')
username_AAA = input('Please enter your AAA username:')
password_AAA = getpass.getpass('Please enter your AAA Password:')

print('connecting to XXX')
log_file = open('log_aaa.txt', 'wb')
child = pexpect.spawn('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ' + username + '@XX.XXX.XX.XX', timeout=60)
child.logfile_read = log_file
child.expect('password:')
child.sendline(password)
child.expect('$')
print('Pinging AAA1 and AAA2 \n\n')
child.sendline('ping XX.XX.XX.XX -c 10')
child.expect('$')
child.sendline('ping XX.X.X.X -c 10')
child.expect('$')
print('Connecting to AAA1 and AAA2 to test connectivity \n\n')
child.sendline('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ' + username_AAA + '@X.X.X.X')
try:
    child.expect('password:')
except pexpect.TIMEOUT:
    raise OurException("Did not catch the pattern")
child.sendline(password_AAA)
# Script goes on a little bit to parse logs but it does not matter
I've done the same process of jumping from the proxy to other servers manually and of course it works. Password prompt received from other servers in proxy ssh server is like this:
Output:
Warning: Permanently added 'X.X.X.X' (RSA) to the list of known hosts. [email protected]'s password:
But "password:" does not get matched Sad Well I'm not very experienced in Python nor Pexpect so I'm looking for some help, guidance... If someone can give a clue I would really appreciate it.
Thanks for your time Smile .
Regards,
Luis

UPDATE:
Well I changed the following line:
child.logfile_read = log_file
for:
child.logfile = log_file
So I get everything the script does. It seems it catches the pattern and sends the commands, passwords and all that. Thing is that spawn child process does not catch the output of the second ssh session (embedded one) and as a consequence nothing is written on the log file.
So I change my question: Does anyone know how to make th spawn child process to catch the output from and embedded ssh session? Smile Smile
Haha thanks in advance for your time.
Regards,
Luis