int情報を出力するスクリプト
ineを基に改造した。
スクリプト
from netmiko import ConnectHandler
import getpass
Routers = {
"R19" : "192.168.122.19",
"R20" : "192.168.122.20",
"R21" : "192.168.122.21",
"R29" : "192.168.122.29",
"R30" : "192.168.122.30",
"R31" : "192.168.122.31"
}
ipaddr = input("Which router do you want to connect?\ne.g. R19\n: ")
uname = input("Please enter your Username: ")
passwd = getpass.getpass("Please enter your Password: ")
router = Routers[ipaddr]
Router = ConnectHandler(ip = router, username = uname, password = passwd, device_type = "cisco_xe")
def rtr_function(dev):
dev.send_command("terminal length 0")
hostname = dev.send_command("show run | in hostname").split()[1]
print(f"*****This is the information of {hostname}'s interface*****")
print("\n")
int = dev.send_command("show ip interface brief | exclude unassigned")
print(int)
print("\n")
dev.disconnect()
rtr_function(Router)
出力例
root@***# python3 output.py
Which router do you want to connect?
e.g. R19
: R30
Please enter your Username: admin
Please enter your Password:
*****This is the information of R30's interface*****
Interface IP-Address OK? Method Status Protocol
GigabitEthernet0/0 10.20.30.30 YES NVRAM up up
GigabitEthernet0/1 10.30.31.30 YES NVRAM up up
Loopback0 150.30.30.30 YES NVRAM up up
Loopback1 172.16.30.30 YES NVRAM up up
Loopback2 172.16.30.31 YES NVRAM up up
root@***#
こだわりポイント
・INEの例だと予めスクリプト内に書いておいたルータのインターフェース情報を一度にすべて出力するが、このスクリプトだとルータを選択することができる
次回へ向けて
・ルータを入力する際、誤った値を入力すると下記の通りPythonの間違い指摘ログが出てくる。これをtry exceptとか使ってエラーメッセージを出力できるようにしたい。
root@***# python3 output.py
Which router do you want to connect?
e.g. R19
: r30
Please enter your Username: admin
Please enter your Password:
Traceback (most recent call last):
File "output.py", line 16, in <module>
router = Routers[ipaddr]
KeyError: 'r30'
root@***#
試行錯誤してる時間も、うまくいったときもめっちゃ楽しい。
CCIE置いといてDevNetやりたくなってきた。
この記事が気に入ったらサポートをしてみませんか?