
本文详细介绍了如何利用python的netmiko库自动化配置cisco路由器,包括ssh连接建立、接口配置(如loopback和物理接口)、ospf路由协议配置以及acl设置。文章重点解析了netmiko `send_config_set` 方法的内部机制,强调无需手动输入 `enable` 和 `configure terminal` 命令,并提供了配置保存、差异比较及常见故障排除的实用指南。
Netmiko是一个强大的Python库,基于Paramiko构建,专门用于简化网络设备的SSH/Telnet连接和配置管理。它抽象了底层连接细节,提供了统一的API来发送命令、配置设备、获取输出等,极大地提高了网络自动化脚本的开发效率和可维护性。通过Netmiko,工程师可以轻松实现批量配置、配置审计、状态收集等任务,减少手动操作的错误率,并加速网络部署和故障排除。
成功自动化配置的第一步是建立稳定的SSH连接。Netmiko通过 ConnectHandler 类管理连接。
以下是建立连接所需的基本参数字典:
device = {
'device_type': 'cisco_ios', # 指定设备类型为Cisco IOS
'host': '192.168.56.101', # 目标设备的IP地址
'username': 'your_username', # 登录用户名
'password': 'your_password', # 登录密码
'secret': 'cisco', # enable模式密码
'port': 22, # SSH默认端口
'timeout': 30, # 连接超时时间(秒)
}使用 with 语句管理 ConnectHandler 实例是最佳实践,它能确保连接在任务完成后自动关闭,即使发生异常。
from netmiko import ConnectHandler
import getpass
import logging
logging.basicConfig(level=logging.INFO)
def main():
host = '192.168.56.101'
username = input('请输入您的用户名: ')
password = getpass.getpass('请输入您的密码: ')
secret = 'cisco' # enable模式密码
device = {
'device_type': 'cisco_ios',
'host': host,
'username': username,
'password': password,
'secret': secret,
'port': 22,
'timeout': 30, # 适当调整超时时间
}
try:
with ConnectHandler(**device) as net_connect:
logging.info('连接已建立')
# 后续配置操作
# ...
except Exception as e:
logging.error(f'发生错误: {e}')
logging.info('连接已结束')
if __name__ == "__main__":
main()故障排除提示:
Netmiko的 send_config_set() 方法是发送配置命令的核心。
关键点: 使用 net_connect.send_config_set() 方法时,Netmiko会自动处理进入和退出特权模式 (enable) 和全局配置模式 (configure terminal) 的过程。因此,在配置命令列表中,无需包含 en 或 conf t 等命令。
错误示例(不推荐):
loopback_config = [
'en\n' # Netmiko会自动处理
'conf t\n' # Netmiko会自动处理
'interface Loopback0\n',
'ip address 192.168.57.101 255.255.255.0\n',
'exit\n'
]这种做法会导致命令重复发送,可能引起设备报错或不必要的延迟。
正确示例:
loopback_config = [
'interface Loopback0',
'ip address 192.168.57.101 255.255.255.0',
'no shutdown' # 确保接口开启
]send_config_set() 会将这些命令逐一发送到设备,并在必要时自动进入和退出配置模式。
以下是如何配置Loopback接口、物理接口和OSPF协议的示例。
def configure_device(net_connect):
"""
向Cisco设备发送一系列配置命令。
"""
# Loopback接口配置
loopback_config = [
'interface Loopback0',
'ip address 192.168.57.101 255.255.255.0',
'no shutdown'
]
# 物理接口GigabitEthernet0/0配置
interface0_config = [
'interface GigabitEthernet0/0',
'ip address 192.168.58.101 255.255.255.0',
'no shutdown'
]
# 物理接口GigabitEthernet0/1配置
interface1_config = [
'interface GigabitEthernet0/1',
'ip address 192.168.59.101 255.255.255.0',
'no shutdown'
]
# 扩展访问控制列表 (ACL) 配置
acl_config = [
'ip access-list extended MY_ACL',
'permit ip 192.168.56.130 0.0.0.255 any', # 注意:这里是通配符掩码
'deny ip any any',
'exit' # 退出ACL配置模式
]
# OSPF协议配置
# 假设router-id为192.168.57.101 (Loopback0的IP)
ospf_config = [
'router ospf 1', # 进程ID为1
'router-id 192.168.57.101', # 建议使用Loopback接口IP作为Router ID
'network 192.168.57.0 0.0.0.255 area 0', # 宣告Loopback0所在网络
'network 192.168.58.0 0.0.0.255 area 0', # 宣告GigabitEthernet0/0所在网络
'network 192.168.59.0 0.0.0.255 area 0', # 宣告GigabitEthernet0/1所在网络
'passive-interface Loopback0', # 仅示例,根据实际需求决定是否配置
'exit' # 退出OSPF配置模式
]
# 合并所有配置命令
all_configs = loopback_config + interface0_config + interface1_config + acl_config + ospf_config
logging.info('正在发送配置命令...')
output = net_connect.send_config_set(all_configs)
print(output) # 打印设备返回的配置结果
logging.info('配置命令发送完成。')注意事项:
自动化配置不仅要能发送命令,还要能验证配置是否成功并进行审计。
配置完成后,通常需要获取设备的运行配置并保存到本地。
def save_config_to_file(config, filename):
"""将配置内容保存到本地文件。"""
with open(filename, 'w') as config_file:
config_file.write(config)
logging.info(f'配置已保存到 {filename}')
# 在主函数中调用
# ...
running_configuration = net_connect.send_command('show running-config')
local_config_file_name = 'running_config_backup.txt'
save_config_to_file(running_configuration, local_config_file_name)
logging.info(f'运行配置已保存到 {local_config_file_name}')
# ...difflib 库可以用来比较两份配置文件的差异,这对于配置审计和故障排除非常有用。
import difflib
def show_differences(config1, config2, name1='配置1', name2='配置2'):
"""显示两份配置之间的差异。"""
difference = difflib.Differ()
diff = list(difference.compare(config1.splitlines(), config2.splitlines()))
logging.warning(f'以下是 {name1} 和 {name2} 之间的差异:')
for line in diff:
if line.startswith('- '):
logging.info(f'- (仅在 {name1} 中): {line[2:]}')
elif line.startswith('+ '):
logging.info(f'+ (仅在 {name2} 中): {line[2:]}')
elif line.startswith('? '):
pass # 忽略difflib生成的问号行
else:
logging.debug(f' (相同): {line[2:]}') # 相同行只在debug级别显示将 show_differences 应用于比较当前运行配置和本地保存的配置:
# ... 在主函数中
# 假设我们已经有了 running_configuration 和 local_config
# 例如,可以先保存一份基线配置为 'baseline_config.txt'
# 然后用 'show running-config' 获得的配置与 'baseline_config.txt' 比较
try:
with open(local_config_file_name, 'r') as local_config_file:
local_config = local_config_file.read()
if running_configuration and local_config:
if running_configuration == local_config:
logging.info('运行配置与本地配置一致。')
else:
logging.warning('运行配置与本地配置不匹配。')
show_differences(local_config, running_configuration,
name1='本地保存配置', name2='当前运行配置')
else:
logging.error('未能获取配置进行比较。')
except FileNotFoundError:
logging.error(f'本地配置文件 ({local_config_file_name}) 未找到。')
# ...结合上述所有功能,以下是一个完整的Netmiko自动化Cisco路由器配置脚本示例:
import logging
import getpass
import difflib
from netmiko import ConnectHandler
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def save_config_to_file(config, filename):
"""将配置内容保存到本地文件。"""
with open(filename, 'w') as config_file:
config_file.write(config)
logging.info(f'配置已保存到 {filename}')
def show_differences(config1, config2, name1='配置1', name2='配置2'):
"""显示两份配置之间的差异。"""
difference = difflib.Differ()
diff = list(difference.compare(config1.splitlines(), config2.splitlines()))
logging.warning(f'以下是 {name1} 和 {name2} 之间的差异:')
for line in diff:
if line.startswith('- '):
logging.info(f'- (仅在 {name1} 中): {line[2:]}')
elif line.startswith('+ '):
logging.info(f'+ (仅在 {name2} 中): {line[2:]}')
elif line.startswith('? '):
pass # 忽略difflib生成的问号行
else:
# logging.debug(f' (相同): {line[2:]}') # 相同行只在debug级别显示
pass
def configure_device(net_connect):
"""
向Cisco设备发送一系列配置命令,包括Loopback、物理接口、ACL和OSPF。
"""
logging.info('正在准备配置命令...')
# Loopback接口配置
loopback_config = [
'interface Loopback0',
'ip address 192.168.57.101 255.255.255.0',
'no shutdown'
]
# 物理接口GigabitEthernet0/0配置
interface0_config = [
'interface GigabitEthernet0/0',
'ip address 192.168.58.101 255.255.255.0',
'no shutdown'
]
# 物理接口GigabitEthernet0/1配置
interface1_config = [
'interface GigabitEthernet0/1',
'ip address 192.168.59.101 255.255.255.0',
'no shutdown'
]
# 扩展访问控制列表 (ACL) 配置
acl_config = [
'ip access-list extended MY_ACL',
'permit ip 192.168.56.130 0.0.0.255 any',
'deny ip any any',
'exit'
]
# OSPF协议配置
ospf_config = [
'router ospf 1',
'router-id 192.168.57.101',
'network 192.168.57.0 0.0.0.255 area 0',
'network 192.168.58.0 0.0.0.255 area 0',
'network 192.168.59.0 0.0.0.255 area 0',
# 'passive-interface Loopback0', # 根据实际需求决定是否配置
'exit'
]
# 合并所有配置命令
all_configs = loopback_config + interface0_config + interface1_config + acl_config + ospf_config
logging.info('正在发送配置命令到设备...')
output = net_connect.send_config_set(all_configs)
print("--- 设备配置输出开始 ---")
print(output)
print("--- 设备配置输出结束 ---")
logging.info('配置命令发送完成。')
def main():
host = '192.168.56.101' # 目标Cisco路由器的IP地址
username = input('请输入您的用户名: ')
password = getpass.getpass('请输入您的密码: ')
secret = getpass.getpass('请输入enable模式密码 (通常为cisco): ') # enable模式密码
choice = input('您想使用telnet还是ssh连接? (telnet/ssh): ').lower()
if choice == 'telnet':
device_type = 'cisco_ios_telnet'
port = 23
elif choice == 'ssh':
device_type = 'cisco_ios'
port = 22
else:
logging.error('无效选择 - 请输入 telnet 或 ssh。')
return
device = {
'device_type': device_type,
'host': host,
'username': username,
'password': password,
'secret': secret,
'port': port,
'timeout': 60, # 增加超时时间以应对网络延迟
}
try:
logging.info(f'尝试连接到设备 {host} ({device_type})...')
with ConnectHandler(**device) as net_connect:
logging.info('连接已成功建立。')
# 发送配置命令
configure_device(net_connect)
# 获取并保存运行配置
logging.info('正在获取设备的运行配置...')
running_configuration = net_connect.send_command('show running-config')
local_config_file_name = 'running_config_after_automation.txt'
save_config_to_file(running_configuration, local_config_file_name)
# 比较配置 (可选,可以与一个基线配置比较)
# 假设我们有一个名为 'baseline_config.txt' 的文件作为基线
baseline_config_file_name = 'baseline_config.txt'
try:
with open(baseline_config_file_name, 'r') as baseline_file:
baseline_config = baseline_file.read()
logging.info(f'正在将当前运行配置与基线配置 ({baseline_config_file_name}) 进行比较...')
show_differences(baseline_config, running_configuration,
name1='基线配置', name2='当前运行配置')
except FileNotFoundError:
logging.warning(f'基线配置文件 ({baseline_config_file_name}) 未找到,跳过差异比较。')
# 也可以再次读取刚刚保存的配置进行比较,验证文件保存是否正确
try:
with open(local_config_file_name, 'r') as saved_file:
saved_config = saved_file.read()
if running_configuration == saved_config:
logging.info('当前运行配置已成功保存到本地文件并保持一致。')
else:
logging.error('警告:运行配置与保存到本地文件的内容不完全一致。')
except FileNotFoundError:
logging.error(f'保存的本地配置文件 ({local_config_file_name}) 未找到以上就是使用Netmiko自动化Cisco路由器配置与故障排除的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号