python-2.7sshenterpexpectpxssh

Enter key command doesn't work sometimes in pexpect


I am running below pexpect script to login to an Avocent console server to connect to a network device. After entering the server password, it requires an 'Enter key' to be pressed for the prompt to appear. To achieve this, I tried child.sendline(), child.send('\n') and child.sendcontrol ('m') but none of these worked. I tried child.send('\r'), but it works intermittently. Not sure what is causing the issue.

I saw that when the script gets stuck waiting for enter key, if I manually login to the console and send the enter key via keyboard, the pexpect script continues.

Here's my code snippet:

child = pexpect.spawn('ssh local@x.x.x.x', timeout=120)
child.expect('Password:', timeout=60)
child.sendline(avocentpswd)
child.send('\r')
print "enter key sent"
cli = child.expect(['cisco#' , 'cisco>'])

Using pexpect==4.7.0 Python 2.7.5 OS: RHEL v7

Could someone please help.

I checked the issues raised, but that didn't help: pexpect and sending an "Enter Key" issues


Solution

  • You probably just need to wait for a second or two for the ssh to finish connecting and reset the tty mode to echo. Try adding a import time;time.sleep(5) before sending the \r, and if it works use a loop something like (not tested):

    for tries in range(5):
       child.send('\r')
       cli = child.expect([pexpect.TIMEOUT, 'cisco#' , 'cisco>'], timeout=1)
       if cli!=0: break
    else: ... fail ...
    ... ok ...