Python netmiko 管理 network devices 簡例

netmiko是python中可用於network device 備份的庫,目前支持的設備如下:
As of June 2015, Netmiko has support for the following platforms:
Cisco IOS
Cisco IOS-XE
Cisco ASA
Cisco NX-OS
Cisco IOS-XR
Cisco WLC (limited testing)
Arista EOS
HP ProCurve
HP Comware (limited testing)
Juniper Junos
Brocade VDX (limited testing)
F5 LTM (experimental)
Huawei (limited testing)

下面是一段使用netmiko庫登陸ciscorouter 3360 的python代碼

from netmiko import ConnectHandler

#要連接設備的信息,順序不重要

cisco = {
    'device_type':'cisco_ios',
    'ip':'192.168.60.222',
    'username':'admin',
    'password': 'password',
    'secret':'google',   #enable password
}

#進行ssh連接

connect=ConnectHandler(**cisco)     #對於兩個*號,我的理解是:ConnectHandler()函數需要在cisco字典裏面找"兩"個東西,key和對應的value,所以用兩個*星號

#如果enable有密碼需要在配置連接的時候配置,例如 'secret':'google' ,輸入connect.send_command('enable') 是無效的

connect.enable()   #相當於進入特權模式
output_1 = connect.send_command('show run')
print("show run 的輸出如下:\n"+output_1)
print("----------------------")

#輸入connect.send_command('config ter')是進不了配置模式的,需要配置直接輸入connect.send_config_set('cli')

out_put_2 = connect.send_config_set('ip route 0.0.0.0 0.0.0.0 192.168.60.129')  #相當於輸入特權模式 + 輸入配置命令
print("配置默認路由後的輸出:\n\n"+out_put_2+"\n\n")          #輸出配置過程

#查看上述的配置是否生效

show_route = connect.send_command('show ip route') #send_command('cli')命令執行的結果只能在本級,不能exit或者 enable、configure terminal
print("查看路由條目:\n"+show_route)
——————————————————————————————————————————————————————————————————————————
上述文件的輸出如下(因篇幅問題,有部分會有刪除):
1、show run 的輸出如下:
Building configuration...

Current configuration : 874 bytes
!
version 12.4
service timestamps debug datetime msec
service timestamps log datetime msec

 logging synchronous
line aux 0
 exec-timeout 0 0
 privilege level 15
 logging synchronous
line vty 0 4
 login local
!
!
end

----------------------

2、配置默認路由後的輸出:

config term
Enter configuration commands, one per line.  End with CNTL/Z.
R1(config)#ip route 0.0.0.0 0.0.0.0 192.168.60.129
R1(config)#end
R1#

3、查看路由條目:
Codes: C - connected, S - static, R - RIP, M - mobile, B - BGP
       D - EIGRP, EX - EIGRP external, O - OSPF, IA - OSPF inter area 
       N1 - OSPF NSSA external type 1, N2 - OSPF NSSA external type 2
       E1 - OSPF external type 1, E2 - OSPF external type 2
       i - IS-IS, su - IS-IS summary, L1 - IS-IS level-1, L2 - IS-IS level-2
       ia - IS-IS inter area, * - candidate default, U - per-user static route
       o - ODR, P - periodic downloaded static route

Gateway of last resort is 192.168.60.129 to network 0.0.0.0

C    192.168.60.0/24 is directly connected, FastEthernet0/0
S*   0.0.0.0/0 [1/0] via 192.168.60.129

Process finished with exit code 0

參考鏈接:
①https://pypi.python.org/pypi/netmiko/1.4.1
②https://pynet.twb-tech.com/blog/automation/netmiko.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章