Python: Network Automation with Pexpect

1 minute read

Updated:

Pexpect

Pexpect makes Python a better tool for controlling other applications.

Pexpect is a pure Python module for spawning child applications; controlling them; and responding to expected patterns in their output. Pexpect allows your script to spawn a child application and control it as if a human were typing commands.

Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc.

We will use our topology as below:

picture

Lab Configuration same as previous.

Installation

Pexpect is on PyPI, and can be installed with standard tools:

pip install pexpect

Or:

easy_install pexpect

Example of Pexpect

Below is the python code for achieving our task. Write the code using a nano editor as exe_01.py.

""" 
1. The expect() method in Pexpect process is an indicator for the 
returned string from the remote device.
2. The sendline() method indicates which words should be sent to the
remote device as the command.
"""
""" 
1. The expect() method in Pexpect process is an indicator for the 
returned string from the remote device.
2. The sendline() method indicates which words should be sent to the
remote device as the command.
"""
import pexpect

child = pexpect.spawn('telnet 192.168.10.10')
child.expect('Username: ')  # child.expect('[Uu]sername: ')
child.sendline('admin')
child.expect('Password: ')  # child.expect(['Password', 'password'])
child.sendline('cisco')
child.expect('S1>')
child.sendline('enable')
child.expect('Password: ')
child.sendline('cisco')
child.expect('S1#')
child.sendline('show version | i V')
child.expect('S1#')
# convert it to a string
show_output = child.before.decode('utf-8')
# print out the command 
print(show_output) 
child.sendline('exit')

SSH basic code sample

import pexpect

child = pexpect.spawn('ssh admin@192.168.10.10')
child.expect('Password: ')
child.sendline('cisco')
child.expect('S1>')
child.sendline('enable')
child.expect('Password: ')
child.sendline('cisco')
child.expect('S1#')
child.sendline('show version | i V')
child.expect('S1#')
# convert it to a string
show_output = child.before.decode('utf-8')
# print out the command 
print(show_output) 
child.sendline('exit')

More script at GitHub

Comments