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

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'
主站蜘蛛池模板: 登封市| 安顺市| 张掖市| 霞浦县| 海南省| 六枝特区| 曲周县| 迁西县| 手游| 伊吾县| 定结县| 仁怀市| 宜都市| 正镶白旗| 林口县| 文水县| 合川市| 年辖:市辖区| 景洪市| 黑山县| 进贤县| 务川| 桐庐县| 临桂县| 克拉玛依市| 阳春市| 碌曲县| 平和县| 兴文县| 杨浦区| 涡阳县| 绩溪县| 易门县| 兴仁县| 清涧县| 无极县| 双辽市| 双城市| 蚌埠市| 磐安县| 汪清县|