如何使用Python脚本批量登录交换机?

前言:

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: bunian1
  password: bunian123
  port: 22

SW02:
  device_type: cisco_ios
  host: 10.0.0.2
  username: bunian2
  password: bunian456
  port: 22

SW03:
  device_type: huawei
  host: 10.0.0.3
  username: bunian3
  password: bunian789
  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 -> <Huawei>

代码解释:

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': 'bunian1', 
    'password': 'bunian123', 
    'port': 22
  }, 
  'SW02': {
    'device_type': 'cisco_ios', 
    'host': '10.0.0.2', 
    'username': 'bunian2', 
    'password': 'bunian456', 
    'port': 22
  }, 
  'SW03': {
    'device_type': 'huawei', 
    'host': '10.0.0.3', 
    'username': 'bunian3', 
    'password': 'bunian789', 
    '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!')
© 版权声明
THE END
喜欢就支持一下吧
点赞82赞赏 分享
评论 抢沙发
头像
欢迎光临不念博客,留下您的想法和建议,祝您有愉快的一天~
提交
头像

昵称

取消
昵称代码图片

    暂无评论内容