前言:
Environment:python = 3.9.0netmiko = 4.1.0 (pip install netmiko)pyyaml = 6.0 (pip install pyyaml)
文件内容
为方便以后管理,使用YAML文件作为设备库(也可以使用json,但YAML更直观:)。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 |
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) |
| |
| { |
| '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(): |
| |
| 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!') |