- Mastering Python Networking
- Eric Chou
- 179字
- 2021-07-02 21:42:36
Our first Expect program
Our first program extends what we have done in the last section with some additional code:
#!/usr/bin/python3
import pexpect
devices = {'iosv-1': {'prompt': 'iosv-1#', 'ip': '172.16.1.20'}, 'iosv-2': {'prompt': 'iosv-2#', 'ip': '172.16.1.21'}}
username = 'cisco'
password = 'cisco'
for device in devices.keys():
device_prompt = devices[device]['prompt']
child = pexpect.spawn('telnet ' + devices[device]['ip'])
child.expect('Username:')
child.sendline(username)
child.expect('Password:')
child.sendline(password)
child.expect(device_prompt)
child.sendline('show version | i V')
child.expect(device_prompt)
print(child.before)
child.sendline('exit')
We use a nested dictionary in line 5:
devices = {'iosv-1': {'prompt': 'iosv-1#', 'ip':
'172.16.1.20'}, 'iosv-2': {'prompt': 'iosv-2#',
'ip': '172.16.1.21'}}
The nested dictionary allows us to refer to the same device (such as iosv-1) with the appropriate IP address and prompt symbol. We can then use those values for the expect() method later on in the loop.
The output prints out the 'show version | i V' output on the screen for each of the devices:
$ python3 chapter2_1.py
b'show version | i VrnCisco IOS Software, IOSv
Software (VIOS-ADVENTERPRISEK9-M), Version 15.6(2)T,
RELEASE SOFTWARE (fc2)rnProcessor board ID
9MM4BI7B0DSWK40KV1IIRrn'
b'show version | i VrnCisco IOS Software, IOSv
Software (VIOS-ADVENTERPRISEK9-M), Version 15.6(2)T,
RELEASE SOFTWARE (fc2)rn'
推薦閱讀
- Practical Data Analysis Cookbook
- C和C++安全編碼(原書第2版)
- Python從菜鳥到高手(第2版)
- C語言程序設計教程(第2版)
- Groovy for Domain:specific Languages(Second Edition)
- MATLAB定量決策五大類問題
- Node.js Design Patterns
- Haskell Data Analysis Cookbook
- 深入淺出React和Redux
- Procedural Content Generation for C++ Game Development
- Windows Embedded CE 6.0程序設計實戰
- JavaScript程序設計(第2版)
- Java并發編程:核心方法與框架
- Distributed Computing in Java 9
- Tableau Desktop可視化高級應用