CrossingTheRoad2020
CrossingTheRoad2020

Reputation: 61

Pexect in Windows Batch File > Cygwin > Python > SSH

I have a Linux box that runs Cisco IOS and need to SSH into it sometimes to reboot it. I've written a batch file that calls on Cygwin. Cygwin then calls on Python+PythonScript.

Batch File:

cd c:\cygwin64\bin
bash --login -i -c "python3 /home/Owner/uccxtesting.py"

Python Script

import pexpect
import time
import sys

server_ip = "10.0.81.104"
server_user = "administrator"
server_pass = "secretpassword"

sshuccx1 = pexpect.spawn('ssh %s@%s' % (server_user, server_ip))
sshuccx1.logfile_read = sys.stdout.buffer
sshuccx1.timeout = 180
sshuccx1.expect('.*password:')
sshuccx1.sendline(server_pass)
sshuccx1.expect('.admin:')
sshuccx1.sendline('utils system restart')
sshuccx1.expect('Enter (yes/no)?')
sshuccx1.sendline('yes')
time.sleep(30)

When I run this, it stops at Enter yes/no. This is what I'm getting:

enter image description here

I've seen plenty of examples of pexpect with expect, but there is some white space out beside the question mark. I just don't know how to tell python to expect it.

Upvotes: 0

Views: 222

Answers (1)

Rob G
Rob G

Reputation: 683

There may be a bug:

utils system restart prompts for force restart (https://bst.cisco.com/bugsearch/bug/CSCvw22828)

Replace time.sleep(30) with the following code to answer a possible force restart prompt. If it works, you can get rid of the try...except and print commands that I added for debugging:

try:
    index = -1
    while index != 0:
        sshuccx1.expect_exact(['succeeded', 'force', ], timeout=300)
        if index == 2:
            print('Forcing restart...')
            sshuccx1.sendline('yes')
    print('Operation succeeded')
    print(str(child.before))
except pexpect.ExceptionPexpect:
    e_type, e_value, _ = sys.exc_info()
    print('Error: ' + pexpect.ExceptionPexpect(e_type).get_trace())
    print(e_type, e_value)

Also, change sshuccx1.expect('Enter (yes/no)?') to sshuccx1.expect_exact('Enter (yes/no)?'). The expect method tries to match a regex pattern, and it may get caught on the parentheses (see https://pexpect.readthedocs.io/en/stable/api/pexpect.html#pexpect.spawn.expect_exact)

Upvotes: 1

Related Questions