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

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'
主站蜘蛛池模板: 通许县| 彭山县| 玛曲县| 曲松县| 蒲城县| 安顺市| 交口县| 兰西县| 交口县| 黄骅市| 手游| 东明县| 石台县| 浙江省| 靖江市| 武义县| 沙河市| 平罗县| 图木舒克市| 孟连| 漳州市| 台南市| 保靖县| 苏尼特左旗| 沭阳县| 贡觉县| 宿州市| 广南县| 盱眙县| 琼海市| 藁城市| 永川市| 岫岩| 如东县| 海口市| 凤阳县| 汝南县| 新邵县| 忻州市| 友谊县| 锡林郭勒盟|