- 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'
推薦閱讀
- Learning Single:page Web Application Development
- Microsoft Dynamics 365 Extensions Cookbook
- PostgreSQL Cookbook
- TestNG Beginner's Guide
- 愛上micro:bit
- 軟件供應(yīng)鏈安全:源代碼缺陷實例剖析
- HTML+CSS+JavaScript編程入門指南(全2冊)
- Python語言科研繪圖與學術(shù)圖表繪制從入門到精通
- IDA Pro權(quán)威指南(第2版)
- Struts 2.x權(quán)威指南
- Mastering Embedded Linux Programming
- Python Social Media Analytics
- Access數(shù)據(jù)庫應(yīng)用教程(2010版)
- Microsoft Exchange Server 2016 PowerShell Cookbook(Fourth Edition)
- Python數(shù)據(jù)預(yù)處理技術(shù)與實踐