官术网_书友最值得收藏!

Putting things together for Pexpect

As the final step, let's put everything you learned so far for Pexpect into a script. Putting the code in a script makes it easier to use it in a production environment as well as share the code with your colleagues.

You can download the script from the book GitHub repository, https://github.com/PacktPublishing/Mastering-Python-Networking as well as look at the output generated from the script as a result of the commands.
  #!/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 on our first Pexpect program with the following additional features:

  • It use SSH instead of telnet
  • It supports multiple commands instead of just one by making the commands into a list (line 8) and loop through the commands (starting line 20)
  • It prompts the user for username and password instead of hardcoding them in the script
  • It writes the output into a file to be further analyzed
For Python 2, use raw_input() instead of input() for the username prompt. Also use w for file mode instead of wb.
主站蜘蛛池模板: 永丰县| 阳东县| 沙坪坝区| 泾阳县| 峨眉山市| 景东| 山丹县| 阳东县| 仪征市| 凤山市| 安阳市| 阿巴嘎旗| 北海市| 青阳县| 洛隆县| 高青县| 佛坪县| 阜阳市| 蒲城县| 屯留县| 淮北市| 湖南省| 静海县| 康平县| 颍上县| 阳泉市| 新巴尔虎左旗| 建水县| 喀什市| 孟村| 昂仁县| 米脂县| 左贡县| 蒙阴县| 寻乌县| 海兴县| 阿合奇县| 平利县| 武冈市| 天台县| 称多县|