Python 网络自动化脚本示例

在这篇文章中,我将详细介绍一些我几乎每天都在使用的 Cisco 网络工程师的 Python 脚本。

对于每个需要连接的示例,我将使用 20 个 CSR 路由器的基本拓扑。

我还将使用 Netmiko 连接到网络设备。如果您之前没有使用过 Netmiko,那么您可以查看使用 Netmiko 创建到 Cisco 路由器的连接的快速运行。

 
 
 
 

如果您被告知需要学习或实施网络自动化,这些脚本应该可以帮助您入门。

Python 网络自动化正在成为 2021 年的必备技能。因此,您需要确保了解您的对象、变量、方法、函数、字典和列表。作为当今最流行的编程语言之一,可用的信息非常多,下面的脚本应该可以帮助您入门。

如果您是 Python 新手,您可以查看我的Python 初学者教程

如果要下载下面使用的所有脚本,可以使用以下命令
git clone存储库:git clone https://github.com/rogerperkin/python-scripts-for-network-engineers.git

页面内容[显示]

1. Cisco Python 脚本通过 SSH 连接到路由器

我将向您展示的第一个脚本是如何通过 SSH 连接到路由器。

该脚本使用 Netmiko 建立连接,然后我将运行“show ip interface brief”命令来验证路由器上的 ip 接口。

Github 上的脚本:ssh-to-router.py

from netmiko import ConnectHandler
 
#First create the device object using a dictionary
CSR = {
    'device_type': 'cisco_ios',
    'ip': '192.168.1.220',
    'username': 'roger',
    'password': 'cisco'
}
 
# Next establish the SSH connection
net_connect = ConnectHandler(**CSR)
 
# Then send the command and print the output
output = net_connect.send_command('show ip int brief')
print (output)
 
# Finally close the connection
net_connect.disconnect()
 

这是一个非常基本的脚本,它首先从 Netmiko 导入 ConnectHandler。

注意:要运行它,您必须先安装 Netmiko——如果还没有安装,请观看本文顶部的视频。

然后我们定义一个名为 CSR 的设备并提供 Netmiko 所需的信息,即device_typeIP 地址以及用户名密码

然后使用 net_connect 模块连接到设备 CSR

连接后,我们将命令“sh ip int brief”发送到路由器并将值保存为输出

最后,我们打印输出并断开与设备的连接。

2. SSH 到多个路由器

现在我们有一个到单个路由器的基本连接,是时候扩展它了,我们现在要连接到 5 个路由器。但它很容易是 100 或 1000!

ssh-to-multiple-routers.py

为此,我创建了一个名为 devices.txt 的新文件,其中包含我们 5 个 CSR 路由器的所有 IP 地址。然后我们使用相同的脚本,但循环连接并传入每个路由器的 IP,这样我们就可以获得所有路由器的“sh ip int brief”输出。

192.168.1.220
192.168.1.221
192.168.1.222
192.168.1.223
192.168.1.224
192.168.1.225

注意:不要在最后一行的末尾按回车键。否则你的脚本最后会出现问题。

# SSH to Multiple Devices from devices file
from netmiko import ConnectHandler
 
with open('devices.txt') as routers:
    for IP in routers:
        Router = {
            'device_type': 'cisco_ios',
            'ip': IP,
            'username': 'roger',
            'password': 'cisco'
        }
 
        net_connect = ConnectHandler(**Router)
 
        print ('Connecting to ' + IP)
        print('-'*79)
        output = net_connect.send_command('sh ip int brief')
        print(output)
        print()
        print('-'*79)
 
# Finally close the connection
net_connect.disconnect()
 

如果您正在大规模执行此操作,您将使用 Python 自动化框架,如Nornir。这为您提供了库存的好处,就像 Ansible 一样。

但是,在跳转到其他主题之前了解如何手动执行此任务仍然很好。

3. 用于备份 Cisco 配置的 Python 脚本

现在我们已经确定了如何连接到多个设备并可以运行基本命令,下一步是能够保存该输出。

人们在开始使用网络自动化时通常会执行的首要任务之一是备份配置文件。这个 Python 脚本就是这样做的。

备份路由器.py

from netmiko import ConnectHandler
 
#First create the device object using a dictionary
CSR = {
    'device_type': 'cisco_ios',
    'ip': '192.168.1.220',
    'username': 'roger',
    'password': 'cisco'
}
 
# Next establish the SSH connection
net_connect = ConnectHandler(**CSR)
 
#Discover the hostname from the prompt
 
hostname = net_connect.send_command('show run | i host')
hostname.split(" ")
hostname,device = hostname.split(" ")
print ("Backing up " + device)
 
filename = '/home/roger/python-scripts-for-network-engineers/backups/' + device + '.txt'
# to save backup to same folder as script use below line and comment out above line
# filename = device + '.txt'
 
showrun = net_connect.send_command('show run')
showvlan = net_connect.send_command('show vlan')
showver = net_connect.send_command('show ver')
log_file = open(filename, "a")   # in append mode
log_file.write(showrun)
log_file.write("\n")
log_file.write(showvlan)
log_file.write("\n")
log_file.write(showver)
log_file.write("\n")
 
# Finally close the connection
net_connect.disconnect()

注意:您需要更改 filename = 以匹配您的环境

继续阅读以获取更多 Cisco Python 脚本示例。

4. 备份多个路由器的Python脚本

现在我们有了一个可以备份单个 Cisco 路由器的脚本,很容易使用我们用来连接多个路由器的脚本并将备份任务添加到 for 循环中。

该脚本再次使用 devices.txt 文件来遍历 IP 列表并备份每个路由器。

所有备份都放在 /backups 中,但您可以通过更改文件名后的路径来更改备份的位置。

备份多路由器.py

# SSH to Multiple Devices from devices file
from netmiko import ConnectHandler
 
with open('devices.txt') as routers:
    for IP in routers:
        Router = {
            'device_type': 'cisco_ios',
            'ip': IP,
            'username': 'roger',
            'password': 'cisco'
        }
 
        net_connect = ConnectHandler(**Router)
 
        hostname = net_connect.send_command('show run | i host')
        hostname.split(" ")
        hostname,device = hostname.split(" ")
        print ("Backing up " + device)
 
        filename = '/home/roger/python-scripts-for-network-engineers/backups/' + device + '.txt'
        # to save backup to same folder as script use below line and comment out above line
        # filename = device + '.txt'
 
        showrun = net_connect.send_command('show run')
        showvlan = net_connect.send_command('show vlan')
        showver = net_connect.send_command('show ver')
        log_file = open(filename, "a")   # in append mode
        log_file.write(showrun)
        log_file.write("\n")
        log_file.write(showvlan)
        log_file.write("\n")
        log_file.write(showver)
        log_file.write("\n")
 
# Finally close the connection
net_connect.disconnect()

5. 使用 Jinja2 的配置生成器。

待定

6. IP 有效检查器

这个简单的 Python 脚本使用 ipaddress 模块,并将验证输入的 IPv4 或 IPv6 地址是否有效。

import os, ipaddress
 
os.system('cls')
 
while True:
    ip = input('Enter IP Address: ')
    try:
        print(ipaddress.ip_address(ip))
        print('IP Valid')
    except:
        print:('-' *50)
        print('IP is not valid')
    finally:
        if ip =='q':
           print('Script Finished')
           break

此页面正在不断开发中,当我使用新脚本时,我将在此处添加它。

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值