上QQ阅读APP看书,第一时间看更新
Putting things together for Pexpect
As the final step, let's put everything you have learned so far about Pexpect into a script. Putting code into a script makes it easier to use in a production environment, as well as easier to share with your colleagues. We will write our second script, chapter5_2.py.
You can download the script from the book GitHub repository, https://github.com/PacktPublishing/Python-Network-Programming, as well as looking at the output generated from the script as a result of the commands.
Refer to the following code:
#!/usr/bin/python3
import getpass
from pexpect import pxssh
devices = {'iosv-1': {'prompt': 'iosv-1#', 'ip': '172.16.1.20'},
'iosv-2': {'prompt': 'iosv-2#', 'ip': '172.16.1.21'}}
commands = ['term length 0', 'show version', 'show run']
username = input('Username: ')
password = getpass.getpass('Password: ')
# Starts the loop for devices
for device in devices.keys():
outputFileName = device + '_output.txt'
device_prompt = devices[device]['prompt']
child = pxssh.pxssh()
child.login(devices[device]['ip'], username.strip(), password.strip(), auto_promp t_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()
The script further expands from our first Pexpect program with the following additional features:
- It uses SSH instead of Telnet
- It supports multiple commands instead of just one by making the commands into a list (line 8) and loops through the commands (starting at line 20)
- It prompts the user for their username and password instead of hardcoding them in the script
- It writes the output in two files, iosv-1_output.txt, and ios-2_output.txt, to be further analyzed
For Python 2, use raw_input() instead of input() for the username prompt. Also, use w for the file mode instead of wb.