Python自动化运维-netmiko模块设备自动发现

四个拥有:无论你有多弱或多强,一定要拥有真正爱你的人,拥有知心的朋友,拥有向上的事业,拥有温暖的住所。

netmiko提供了一种可以“猜测”的设备类型和发现设备的机制。通过组合使用SNMP发现OIDS和在远程控制台上执行多个show命令这两种方式,根据输出字符串检测设备的操作系统和类型。然后netmiko将相应的驱动程序加载到ConnectHandle()类中。

交换机开启SSH连接功能

<Huawei>system-view 
[huawei]aaa
[Huawei-aaa]local-user huajiao238 password cipher huajiao238 privilege level 15     #权限等级按需求给
[Huawei-aaa]local-user huajiao238 service-type ssh     #给用户绑定服务类型
[Huawei-aaa]quit
[huawei]ssh user huajiao238 authentication password   #密码认证,看你情况选择,如果选择秘钥,记得要生成秘钥哈
[huawei]ssh user huajiao238 service-type stelnet
[huawei]stelnet server enable    #开始ssh服务
[huawei]user-interface vty 0
[Huawei-ui-vty0]authentication-mode aaa   #认证模式为aaa,认证、授权、计费(authentication,authorization,accounting)
[Huawei-ui-vty0]protocol inbound ssh    #只允许SSH进行连接    选配,看实际需求

python处理

netmiko模块的安装及使用在前面发过,以下为链接,不会的朋友可进去喵一眼。

Python自动化运维—netmiko模块连接并配置华为交换机
haodaima.com2年前
3632620
from netmiko import SSHDetect

device_info = {
    'device_type':'autodetect',
    'host':'192.168.100.2',
    'username':'huajiao238',
    'password':'huajiao238'
}

connect = SSHDetect(**device_info)
device_type = connect.autodetect()
print(device_type)
print(connect.potential_matches)

结果输出:

D:\pythonProject\demo\demo\venv\Scripts\python.exe D:/pythonProject/demo/demo/demo.py
huawei
{'huawei': 99}

Process finished with exit code 0

输出匹配度最高的设备类型

from netmiko import SSHDetect, Netmiko

device_info = {
    'device_type':'autodetect',
    'host':'192.168.100.2',
    'username':'huajiao238',
    'password':'huajiao238'
}

detect = SSHDetect(**device_info)
device_type = detect.autodetect()
print(device_type)
print(detect.potential_matches)
device_info['device_type'] = device_type     #将自动获取到的设备类型赋给device_info中device_type
connect = Netmiko(**device_info)

在上面的代码中,需要注意一下几点:

首先,设备字典中的device_type等于autodetect,也就是告诉netmiko在检测到设备类型之前不要加载驱动程序。

然后,使用netmiko的SSHDetect()类发现设备。它使用SSH连接到设备,并执行一些命令以找出操作系统的类型,结果以字典形式返回。

接着,使用autodetect()函数将匹配度最高的结果赋给device_type变量。

接下来,输出potential_matches,查看字典内的全部返回结果。netmiko的设备商支持列表中没有H3C,如果有,那么可能会同时匹配两种设备。

最后,可以更新设备字典并为其分配新的device_type。

到此这篇关于Python自动化运维-netmiko模块设备自动发现就介绍到这了。世上没有一件工作不辛苦,没有一处人事不复杂。在外很不容易,努力过后才知道许多事情,坚持坚持就过来了,一觉醒来又是满血复活的一天。更多相关Python自动化运维-netmiko模块设备自动发现内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

标签: Python netmiko