栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

(2022) netmiko - 1.批量登录交换机

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

(2022) netmiko - 1.批量登录交换机

前言:

Environment:
python = 3.9.0
netmiko = 4.1.0 (pip install netmiko)
pyyaml = 6.0 (pip install pyyaml)

文件内容

为方便以后管理,使用YAML文件作为设备库(也可以使用json,但YAML更直观:)。
inventory.yml 如下:

# inventory.yml
SW01:
  device_type: cisco_ios
  host: 10.0.0.1
  username: user1
  password: user123
  port: 22

SW02:
  device_type: cisco_ios
  host: 10.0.0.2
  username: user2
  password: user456
  port: 22

SW03:
  device_type: huawei
  host: 10.0.0.3
  username: user3
  password: user789
  port: 22
  conn_timeout: 15 # 华为S5720交换机假如连接超时的话加上

main.py 如下:

# main.py
import yaml
from netmiko import ConnectHandler
from netmiko.exceptions import NetmikoTimeoutException, NetmikoAuthenticationException

with open('inventory.yml', 'r') as f:
    devs = yaml.safe_load(f)

for hostname, conn_info in devs.items():
    conn_info.setdefault('session_log', f'{hostname}_logs.txt')
    try:
        with ConnectHandler(**conn_info) as conn:
            print(f'[{hostname}] connected -> {conn.find_prompt()}')
    except NetmikoTimeoutException:
        print(f'ERROR: [{hostname}] connect timeout!')
    except NetmikoAuthenticationException:
        print(f'ERROR: [{hostname}] please check your username & password!')
输出效果
$ python main.py
ERROR: [SW01] connect timeout!
ERROR: [SW02] please check your username & password!
[SW03] connected -> 
代码解释: 1. 从设备库中读取设备参数为字典格式:
import yaml
with open('inventory.yml', 'r') as f:
    devs = yaml.safe_load(f)
# print(devs)
{
  'SW01': {
    'device_type': 'cisco_ios', 
    'host': '10.0.0.1', 
    'username': 'user1', 
    'password': 'user123', 
    'port': 22
  }, 
  'SW02': {
    'device_type': 'cisco_ios', 
    'host': '10.0.0.2', 
    'username': 'user2', 
    'password': 'user456', 
    'port': 22
  }, 
  'SW03': {
    'device_type': 'huawei', 
    'host': '10.0.0.3', 
    'username': 'user3', 
    'password': 'user789', 
    'port': 22, 
    'conn_timeout': 15
  }
}
2. 利用读取的设备字典,通过netmiko连接,捕捉连接超时和验证错误,同时记录日志。
from netmiko import ConnectHandler
from netmiko.exceptions import NetmikoTimeoutException, NetmikoAuthenticationException
for hostname, conn_info in devs.items():
    # 添加参数,将登录过程记录到同目录下的“{设备名}_logs.txt” (也可以在inventory.yml里设置)
    conn_info.setdefault('session_log', f'{hostname}_logs.txt')
    try:
        with ConnectHandler(**conn_info) as conn:
            print(f'[{hostname}] connected -> {conn.find_prompt()}')
    except NetmikoTimeoutException: # 连接超时
        print(f'ERROR: [{hostname}] connect timeout!')
    except NetmikoAuthenticationException: # 验证失败
        print(f'ERROR: [{hostname}] please check your username & password!')
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/935081.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号