Search code examples
pythonsshciscopexpect

Learning to use python to SSH into switches


I am learning pexpect and regular expressions. I have two questions: 1. Does child.expect(some text here) actually have to be a regular expression? 2. If anyone could tell my why my script hangs on password entry, it would be greatly appreciated.

import pexpect
import getpass
import sys

try:
    switch = raw_input("Host: ")
    un = raw_input("Username: ")
    pw = getpass.getpass("Password: ")

    child = pexpect.spawn("ssh %s@%s" % (un, switch))
    child.logfile = sys.stdout

    selection = child.expect(['Are you sure you want to continue connecting (yes/no)?','login as:'])

    if selection == 0:
        child.sendline("yes")

    elif selection == 1:
        i = child.expect(['login as:','[email protected]\'s password:'])
        if i == 0:
            child.sendline(un)
        elif i == 1:
            child.sendline(pw)

    child.expect('Switch#')
    child.sendline("show cdp nei")

except Exception as e:
    print("Failed on login")
    print(e)

Solution

  • From the docs:

    … The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled to re types. …

    So, if you pass a pattern like this:

    ['Are you sure you want to continue connecting (yes/no)?','login as:']
    

    … that's a list of two strings, which will both be compiled to regular expressions. So, e.g., you'll have a capturing group containing the single value yes/no, appearing 0 or 1 times, which probably isn't very useful.

    If you want to match them as literal strings, the simplest thing to do is probably call re.escape on them:

    [re.escape('Are you sure you want to continue connecting (yes/no)?'),
     re.escape('login as:')]