简体   繁体   中英

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:','user@10.0.0.65\'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)

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, eg, 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:')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM