- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
04-24-2023 11:47 AM - edited 05-05-2023 11:48 AM
Automate Shell Interaction in Python with Pexpect
Expect is a command/scripting language that talks with your interactive programs or scripts that require user interaction. In a previous Networking Knowledge Base article, we showed how to Automate Shell Scripts with Expect, where we were able to use our Expect code to SSH into a router and have our code interact with it, saving the results in a log file. This saved us the time and effort of typing any commands in the CLI and also reduced human error.
Well, there is a Python library called Pexpect that works just like Expect does, except we can use Python instead of the Expect language. Because Pexpect is written entirely in Python, it doesn’t require TCL or C extensions to be compiled and it allows us the use of Python's syntax and its rich standard library.
1. Install Pexpect with pip
(venv) $ pip install pexpect
2. Save the following code as a Python file and run it. A file will be saved in the same directory it was run from, will be named after the device, and will show the results of the 'show version' and 'show run' commands.
#!/usr/bin/env python
import getpass
from pexpect import pxssh
devices = {'iosxe-latest': {'prompt': 'csr8000v#', 'ip': 'sandbox-iosxe-latest-1.cisco.com', 'username': 'admin', 'password': 'C1sco12345'}}
commands = ['term length 0', 'show version', 'show run']
# Starts the loop for devices
for device in devices.keys():
outputFileName = device + '_output.txt'
device_prompt = devices[device]['prompt']
ip = devices[device]['ip']
username = devices[device]['username']
password = devices[device]['password']
child = pxssh.pxssh()
child.login(ip, username, password, auto_prompt_reset=False)
# Starts the loop for commands and write to output
with open(outputFileName, 'wb') as f:
for command in commands:
child.sendline(command)
child.expect(device_prompt)
f.write(child.before)
child.logout()
A few notes about the code:
- In order to SSH into a router, we use the pxssh subclass, which adds methods for login, logout, and other tricky things in order to handle different situations in the ssh login process.
- The router credentials are the current ones from the IOS XE on CSR Latest Code AlwaysOn1 sandbox. For current sandboxes and credentials, visit the sandbox catalog at https://devnetsandbox.cisco.com/RM/Topology
- The basis for this example was taken from the book Mastering Python Networking, Volume 4, by Eric Chou.
3. Check for the output, saved locally. In this case it's saved as 'iosxe-latest_output.txt'
From the output, saved as 'iosxe-latest_output.txt'
To learn more about Pexpect, see the latest, stable Pexpect docs at https://pexpect.readthedocs.io/en/stable