Python 网络自动化: 使用 Netmiko 模块批量下发华为、思科交换机配置

批量下发华为、思科设备配置

通常我们对较多交换机进行配置变更的时候,都是通过人为 Login 设备,将需要变更的指令输入进去。这不仅效率低,容易出错,而且对做重复事情的厌恶情绪会直接影响变更的过程。

由此本文将介绍如何使用 Python Netmiko 模块批量配置交换机的方法。

环境准备(本文采用 Windows 系统)

Python 网络自动化: 使用 Netmiko 模块批量下发华为、思科交换机配置_第1张图片

Python3 安装

打开 Python 下载链接:
https://www.python.org/downloads/release/python-373/

选择对应版本的安装包,点击下载
Python 网络自动化: 使用 Netmiko 模块批量下发华为、思科交换机配置_第2张图片
下载完成后,打开 Python 安装包
安装步骤如下:
一、如图勾选下方的两个选项框,点击 Customize installation 进入下一步安装步骤:
Python 网络自动化: 使用 Netmiko 模块批量下发华为、思科交换机配置_第3张图片
二、所有选项保持默认,点击 Next 进入下一步安装步骤:
Python 网络自动化: 使用 Netmiko 模块批量下发华为、思科交换机配置_第4张图片
三、如图勾选 Install for users 选项,点击 Install 开始安装:
Python 网络自动化: 使用 Netmiko 模块批量下发华为、思科交换机配置_第5张图片
四、等待安装程序完成
Python 网络自动化: 使用 Netmiko 模块批量下发华为、思科交换机配置_第6张图片
五、验证安装结果(以管理员身份运行 CMD)
C:\Users\Administrator> python -V
Python 3.7.3 #控制台输出表示安装成功
六、安装 netmiko 模块(系统自带getpass 模块)
安装 netmiko

C:\Users\Administrator> pip install netmiko
Collecting netmiko

   100% |█████████████████| 1.5MB 436kB/s
   
Successfully installed bcrypt-3.1.7 cffi-1.14.0 cryptography-2.9.2 future-0.18.2 netmiko-3.1.1 paramiko-2.7.1 pycparser-
2.20 pynacl-1.4.0 pyserial-3.4 scp-0.13.2 six-1.15.0 textfsm-1.1.0

验证
C:\Users\Administrator> python
>>> import netmiko
>>> #引入模块无报错,说明模块安装成功

Netmiko模块介绍

当前支持设备类型

Arista vEOS
Cisco ASA
Cisco IOS
Cisco IOS-XE
Cisco IOS-XR
Cisco NX-OS
Cisco SG300
HP ProCurve
Juniper Junos
Linux

Alcatel AOS6/AOS8
Apresia Systems AEOS
Calix B6
Cisco AireOS (Wireless LAN Controllers)
CloudGenix ION
Dell OS9 (Force10)
Dell OS10
Dell PowerConnect
Extreme ERS (Avaya)
Extreme VSP (Avaya)
Extreme VDX (Brocade)
Extreme MLX/NetIron (Brocade/Foundry)
HPE Comware7
Huawei
IP Infusion OcNOS
Juniper ScreenOS
Mellanox
MikroTik RouterOS
MikroTik SwitchOS
NetApp cDOT
Nokia/Alcatel SR OS
OneAccess
Palo Alto PAN-OS
Pluribus
Ruckus ICX/FastIron
Ruijie Networks
Ubiquiti EdgeSwitch
Vyatta VyOS

A10
Accedian
Aruba
Ciena SAOS
Citrix Netscaler
Cisco Telepresence
Check Point GAiA
Coriant
Dell OS6
Dell EMC Isilon
Eltex
Enterasys
Endace
Extreme EXOS
Extreme Wing
Extreme SLX (Brocade)
F5 TMSH
F5 Linux
Fortinet
MRV Communications OptiSwitch
MRV LX
QuantaMesh
Rad ETX
Versa Networks FlexVNF

常用方法

net_connect.send_command() #向下发送命令,返回输出(基于模式)
net_connect.send_command_timing() #沿通道发送命令,返回输出(基于时序)
net_connect.send_config_set() #将配置命令发送到远程设备
net_connect.send_config_from_file() #发送从文件加载的配置命令
net_connect.save_config() #将running#config保存到startup#config
net_connect.enable() #输入启用模式
net_connect.find_prompt() #返回当前路由器提示符
net_connect.commit() #在Juniper和IOS#XR上执行提交操作
net_connect.disconnect() #关闭连接
net_connect.write_channel() #通道的低级写入
net_connect.read_channel() #通道的低级写入

参考链接

https://pynet.twb-tech.com/blog/automation/netmiko.html
https://github.com/ktbyers/netmiko

配置 Python 脚本

一、Cisco

编辑文件,文件命名Cisco_Autoconfig.py

#!/usr/bin/python3
#-*- coding:utf-8 -*-
# ScriptName:  Cisco_Autoconfig.py
# Create Date: 2020-07-08 16:35
# Modify Date: 2020-07-08 16:35
#***************************************************************#
from netmiko import ConnectHandler,NetmikoTimeoutException,NetmikoAuthenticationException #引入netmiko连接模块、报错模块
import getpass #引入密码模块
import time #引入时间模块
date = time.strftime('%Y%m%d', time.localtime()) #赋予date变量
password = getpass.getpass('Password:') #赋予password变量

host={
'192.168.1.10',
'192.168.1.11',
}; #定义需要下发配置的主机 IP

for ip in host: #定义循环
    #创建字典
    cisco_ios = {
    'device_type':"cisco_ios", #定义设备类型
    'ip':ip, #调用变量ip
    'port':'22', #指定端口,默认为22
    'username':'admin', #设备登录名
    'password':password, #调用getpass模块
    #'secret' : 'admin' #enable密码
    }
    try:
	cisco_connect = ConnectHandler(**cisco_ios) #传入设备字典与设备建立SSH连接。
	print ("Sucessfully Login to",ip)
	print ("Building configuration...")
	config = ['ntp server 192.168.1.1','ntp server 192.168.1.2','do show run | sec ntp'] #定义需要配置的命令
	input = cisco_connect.send_config_set(config) #执行命令
	print(input) #打印输出结果
	print(ip,'Was finished!\n',"-"*100)
    except NetmikoAuthenticationException : #认证失败报错记录
	e1 = open(f'{date}.txt','a')
	print(date,ip,'[Error 1] Authentication failed.\n',file = e1)
	e1.close
    except NetmikoTimeoutException : #登录超时报错记录
	e2 = open(f'{date}.txt','a')
	print(date,ip,'[Error 2] Connection timed out.\n',file = e2)
	e2.close
    except : #未知报错记录
	e3 = open(f'{date}.txt','a')
	print(date,ip,'[Error 3] Unknown error.\n',file = e3)
	e3.close
cisco_connect.disconnect() #断开SSH连接

执行脚本

C:\Users\Administrator> python Cisco_Autoconfig.py
Password:   #输入密码
Sucessfully Login to 192.168.1.10
Building configuration...
config term
Enter configuration commands, one per line.
Cisco_C2960_01(config)#ntp server 192.168.1.1
Cisco_C2960_01(config)#ntp server 192.168.1.2
Cisco_C2960_01(config)#do sho run | in ntp
ntp server 192.168.1.1
ntp server 192.168.1.2
Cisco_C2960_01(config)#end
Cisco_C2960_01#
192.168.1.10 Was finished!
---------------------------------------------------------
Sucessfully Login to 192.168.1.11
Building configuration...
config term
Enter configuration commands, one per line.
Cisco_C2960_02(config)#ntp server 192.168.1.1
Cisco_C2960_02(config)#ntp server 192.168.1.2
Cisco_C2960_02(config)#do sho run | in ntp
ntp server 192.168.1.1
ntp server 192.168.1.2
Cisco_C2960_02(config)#end
Cisco_C2960_02#
192.168.1.11 Was finished!
---------------------------------------------------------
C:\Users\Administrator>

当主机出现不可达或者密码错误时,在执行过程中会自动创建以日期命名的 txt 文件,记录失败主机 IP 、时间和原因,如下:

C:\Users\Administrator> more 20200709.txt
20200708 192.168.1.11 [Error 1] Authentication failed.
20200708 192.168.1.12 [Error 2] Connection timed out.
20200708 192.168.1.13 [Error 3] Unknown error.

二、华为

编辑文件,文件命名Huawei_Autoconfig.py

#!/usr/bin/python3
#-*- coding:utf-8 -*-
# ScriptName:  Huawei_Autoconfig.py
# Create Date: 2020-07-08 16:35
# Modify Date: 2020-07-08 16:35
#***************************************************************#
from netmiko import ConnectHandler,NetmikoTimeoutException,NetmikoAuthenticationException #引入netmiko连接模块、报错模块
import getpass #引入密码模块
import time #引入时间模块
date = time.strftime('%Y%m%d', time.localtime()) #赋予date变量
password = getpass.getpass('Password:') #赋予password变量

host={
'192.168.1.10',
'192.168.1.11',
}; #定义需要下发配置的主机 IP

for ip in host: #定义循环
    #创建字典
    huawei = {
    'device_type':"huawei", #定义设备类型
    'ip':ip, #调用变量ip
    'port':'22', #指定端口,默认为22
    'username':'admin', #设备登录名
    'password':password, #调用getpass模块
    #'secret' : 'admin' #enable密码
    }
    try:
	huawei_connect = ConnectHandler(**huawei) #传入设备字典与设备建立SSH连接。
	print ("Sucessfully Login to",ip)
	print ("Building configuration...")
	config = ['命令一''命令二','命令三'] #定义需要配置的命令
	input = huawei_connect.send_config_set(config) #执行命令
	print(input) #打印输出结果
	print(ip,'Was finished!\n',"-"*100)
    except NetmikoAuthenticationException : #认证失败报错记录
	e1 = open(f'{date}.txt','a')
	print(date,ip,'[Error 1] Authentication failed.\n',file = e1)
	e1.close
    except NetmikoTimeoutException : #登录超时报错记录
	e2 = open(f'{date}.txt','a')
	print(date,ip,'[Error 2] Connection timed out.\n',file = e2)
	e2.close
    except : #未知报错记录
	e3 = open(f'{date}.txt','a')
	print(date,ip,'[Error 3] Unknown error.\n',file = e3)
	e3.close
huawei_connect.disconnect() #断开SSH连接

执行结果与 Cisco 类似,就不再演示

参考链接 :

https://mp.weixin.qq.com/s/sYvK86dM2dgYtsyCQw8wAg

你可能感兴趣的:(python编程)