pythonpython-3.xsshpexpectpxssh

Pexpect: Could not set shell prompt


I have referred a python script from https://pexpect.readthedocs.io/en/stable/api/pxssh.html in order to perform a ssh password based login. Code is as follows:

from pexpect import pxssh
import getpass
try:
    s = pxssh.pxssh()
    hostname = input('hostname: ')
    username = input('username: ')
    password = getpass.getpass('password: ')
    s.login(hostname, username, password)
    s.sendline('uptime')   # run a command
    s.prompt()             # match the prompt
    print(s.before)        # print everything before the prompt.
    s.sendline('ls -l')
    s.prompt()
    print(s.before)
    s.sendline('df')
    s.prompt()
    print(s.before)
    s.logout()
except pxssh.ExceptionPxssh as e:
    print("pxssh failed on login.")
    print(e)

When i run the code, it prompts for hostname, username and password. After these inputs are provided through CLI,the ssh login fails with the exception as follows:

could not set shell prompt (received: b"unset PROMPT_COMMAND\r\nPS1='[PEXPECT]\\$ '\r\nUser1@167.254.225.14's password: \r\nUser1@167.254.225.14's password: ", expected: '\\[PEXPECT\\][\\$\\#] ').

The manual login works fine for the same ssh credentials.

Note:
Python version: 3.6
Pexpect version: 4.7 

Solution

  • The error was due to login_timeout which is by default 10 sec. Setting high login_timeout in login() solved the problem.