当前位置:

首页 > 编程开发 > Netmiko高效配置Cisco路由器SSH指南

Netmiko高效配置Cisco路由器SSH指南

本文详细介绍了如何使用Python的Netmiko库通过SSH连接Cisco路由器并进行配置,重点阐述了Netmiko自动处理特权模式和全局配置模式的机制,避免了手动输入en和conft的错误。文章还涵盖了接口IP地址、OSPF协议及ACL的配置方法,并提供了完整的示例代码、配置保存与比较的最佳实践,以及常见的错误处理策略,旨在帮助网络工程师高效自动化Cisco设备的管理。

本文目录

    Netmiko在Cisco路由器上通过SSH进行高效配置与故障排除指南

    本文详细介绍了如何使用Python的Netmiko库通过SSH连接Cisco路由器并进行配置,重点阐述了Netmiko自动处理特权模式和全局配置模式的机制,避免了手动输入`en`和`conf t`的错误。文章还涵盖了接口IP地址、OSPF协议及ACL的配置方法,并提供了完整的示例代码、配置保存与比较的最佳实践,以及常见的错误处理策略,旨在帮助网络工程师高效自动化Cisco设备的管理。

    1. 理解Netmiko的配置模式处理机制

    在使用Netmiko库对Cisco设备进行配置时,一个常见的误区是尝试在发送配置命令前手动输入en(enable)和conf t(configure terminal)命令。Netmiko被设计为简化设备自动化,它在建立连接后会自动处理进入特权模式和全局配置模式的步骤。

    当您通过ConnectHandler成功连接到Cisco IOS设备并提供secret密码时,Netmiko会自动:

    1. 进入特权模式(enable)。
    2. 进入全局配置模式(configure terminal)。

    因此,在您通过net_connect.send_config_set()方法发送配置命令列表时,这些命令将直接在全局配置模式下执行,无需在命令列表中包含en或conf t。如果尝试手动发送这些命令,Netmiko可能会因预期外的输出或命令冲突而导致超时错误。

    错误示例 (应避免):

    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'
    ]

    正确的做法是直接提供配置命令,Netmiko将负责将其送达正确的配置模式。

    2. 建立SSH连接与设备认证

    Netmiko通过ConnectHandler类建立与网络设备的连接。为了实现安全的远程管理,通常推荐使用SSH协议。

    关键参数:

    • device_type: 指定设备类型,对于Cisco IOS设备使用cisco_ios。如果需要Telnet连接,则使用cisco_ios_telnet。
    • host: 目标设备的IP地址或主机名。
    • username: 用于登录设备的用户名。
    • password: 用于登录设备的密码。
    • secret: 进入特权模式(enable mode)所需的密码。
    • port: 连接端口,SSH默认为22,Telnet默认为23。Netmiko通常会根据device_type自动选择。
    • timeout: 操作超时时间(秒),用于控制Netmiko等待设备响应的时间,防止长时间阻塞。

    示例代码片段:

    from netmiko import ConnectHandler
    import getpass
    import logging
    
    logging.basicConfig(level=logging.INFO)
    
    def establish_connection(host, username, password, secret, device_type='cisco_ios', port=22, timeout=60):
        """
        建立与Cisco设备的连接。
        """
        device = {
            'device_type': device_type,
            'host': host,
            'username': username,
            'password': password,
            'secret': secret,
            'port': port,
            'timeout': timeout,
        }
        try:
            net_connect = ConnectHandler(**device)
            logging.info('Connection established successfully.')
            return net_connect
        except Exception as e:
            logging.error(f'Failed to establish connection: {e}')
            raise
    
    # 在主函数中调用
    # net_connect = establish_connection(host, username, password, secret)

    3. 执行设备配置

    Netmiko的send_config_set()方法是发送配置命令列表的首选方式。它会逐条发送命令,并等待设备响应,确保命令被正确执行。

    配置示例:

    3.1 配置Loopback接口

    Loopback接口是逻辑接口,常用于OSPF等路由协议的Router ID或设备管理地址,其状态始终为UP。

    loopback_config = [
        'interface Loopback0',
        'ip address 192.168.57.101 255.255.255.0',
        'no shutdown', # 确保接口开启
        'exit'
    ]

    3.2 配置物理接口

    配置物理接口需要指定接口名称和IP地址。

    interface_config = [
        'interface GigabitEthernet0/0',
        'ip address 192.168.58.101 255.255.255.0',
        'no shutdown',
        'exit',
        'interface GigabitEthernet0/1',
        'ip address 192.168.59.101 255.255.255.0',
        'no shutdown',
        'exit'
    ]

    3.3 配置OSPF协议

    OSPF(Open Shortest Path First)是一种内部网关协议,用于在大型网络中动态交换路由信息。配置OSPF通常涉及定义进程ID、Router ID(通常是Loopback接口IP)和宣告网络。

    ospf_config = [
        'router ospf 1', # OSPF进程ID
        'router-id 192.168.57.101', # 使用Loopback接口IP作为Router ID
        'network 192.168.57.0 0.0.0.255 area 0', # 宣告Loopback网络
        '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网络
        'exit'
    ]

    3.4 配置访问控制列表 (ACL)

    ACL用于过滤网络流量,提供安全控制。

    acl_config = [
        'ip access-list extended MY_ACL',
        'permit ip 192.168.56.130 0.0.0.0 any', # 注意:这里原始问题中的掩码是255.255.255.0,但ACL中通常使用反向掩码,0.0.0.0表示精确匹配主机。
                                             # 如果要匹配192.168.56.130/24,则为 permit ip 192.168.56.0 0.0.0.255 any
        'deny ip any any',
        'exit'
    ]

    整合配置并发送: 将所有配置命令列表合并,然后通过send_config_set()发送。

    def configure_device(net_connect):
        """
        发送配置命令到设备。
        """
        loopback_config = [
            'interface Loopback0',
            'ip address 192.168.57.101 255.255.255.0',
            'no shutdown',
            'exit'
        ]
    
        interface_config = [
            'interface GigabitEthernet0/0',
            'ip address 192.168.58.101 255.255.255.0',
            'no shutdown',
            'exit',
            'interface GigabitEthernet0/1',
            'ip address 192.168.59.101 255.255.255.0',
            'no shutdown',
            'exit'
        ]
    
        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',
            'exit'
        ]
    
        acl_config = [
            'ip access-list extended MY_ACL',
            'permit ip 192.168.56.130 0.0.0.0 any',
            'deny ip any any',
            'exit'
        ]
    
        all_configs = loopback_config + interface_config + ospf_config + acl_config
        logging.info('Sending configuration commands...')
        output = net_connect.send_config_set(all_configs)
        print(output)
        logging.info('Configuration commands sent.')

    4. 配置保存与比较的最佳实践

    自动化配置后,验证配置是否成功并持久化非常重要。

    4.1 保存运行配置

    使用send_command()获取设备的当前运行配置,并将其保存到本地文件。

    def save_config_to_file(config_content, filename):
        """
        将配置内容保存到本地文件。
        """
        with open(filename, 'w') as f:
            f.write(config_content)
        logging.info(f'Configuration saved to {filename}')
    
    # 在连接建立后:
    # running_configuration = net_connect.send_command('show running-config')
    # save_config_to_file(running_configuration, 'router_running_config.txt')

    4.2 比较配置差异

    比较当前运行配置与之前保存的基线配置(或期望配置)是验证变更的有效手段。Python的difflib库可以帮助实现这一点。

    import difflib
    
    def show_differences(config1, config2, label1='Config 1', label2='Config 2'):
        """
        显示两个配置字符串之间的差异。
        """
        difference = difflib.Differ()
        diff = list(difference.compare(config1.splitlines(), config2.splitlines()))
    
        has_diff = False
        for line in diff:
            if line.startswith('- ') or line.startswith('+ '):
                logging.warning(f'Difference found: {line}')
                has_diff = True
        if not has_diff:
            logging.info(f'No significant differences found between {label1} and {label2}.')
        return has_diff
    
    # 示例:比较运行配置与本地保存的配置
    # if running_configuration and local_config:
    #     if running_configuration == local_config:
    #         logging.info('The running configuration is the same as the local configuration.')
    #     else:
    #         logging.warning('The running configuration does not match the local configuration:')
    #         show_differences(local_config, running_configuration, 'Local Config', 'Running Config')

    5. 错误处理与连接管理

    5.1 使用with语句进行连接管理

    Netmiko的ConnectHandler支持上下文管理器(with语句)。使用with语句可以确保连接在代码块执行完毕后自动关闭,即使发生异常也能正确处理,避免了手动调用net_connect.disconnect()可能导致的资源泄露或net_connect未定义错误。

    推荐用法:

    try:
        with ConnectHandler(**device) as net_connect:
            logging.info('Connection established')
            # 在此处执行所有配置和命令操作
            configure_device(net_connect)
            # ... 其他操作
    except Exception as e:
        logging.error(f'An error occurred: {e}')

    在这种模式下,您无需显式调用net_connect.disconnect()。如果需要显式断开,且确保net_connect已定义,则应将其放在with块内部,例如在所有操作完成后,但在with块结束前。但通常情况下,with语句的自动关闭机制已经足够。

    5.2 增强的错误处理

    在整个自动化脚本中,应包含健壮的try-except块来捕获可能发生的网络连接问题、认证失败或命令执行错误。

    6. 完整示例代码

    以下是一个整合了上述所有概念的完整Python脚本,用于通过SSH连接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_content, filename):
        """
        将配置内容保存到本地文件。
        """
        try:
            with open(filename, 'w') as config_file:
                config_file.write(config_content)
            logging.info(f'Configuration saved to {filename}')
        except IOError as e:
            logging.error(f'Failed to save configuration to {filename}: {e}')
    
    def show_differences(config1, config2, label1='Config A', label2='Config B'):
        """
        显示两个配置字符串之间的差异。
        """
        difference = difflib.Differ()
        diff = list(difference.compare(config1.splitlines(), config2.splitlines()))
    
        has_diff = False
        for line in diff:
            if line.startswith('- ') or line.startswith('+ '):
                logging.warning(f'Difference found: {line}')
                has_diff = True
        if not has_diff:
            logging.info(f'No significant differences found between {label1} and {label2}.')
        return has_diff
    
    def configure_device(net_connect):
        """
        发送预定义的配置命令到设备。
        """
        loopback_config = [
            'interface Loopback0',
            'ip address 192.168.57.101 255.255.255.0',
            'no shutdown',
            'exit'
        ]
    
        interface_config = [
            'interface GigabitEthernet0/0',
            'ip address 192.168.58.101 255.255.255.0',
            'no shutdown',
            'exit',
            'interface GigabitEthernet0/1',
            'ip address 192.168.59.101 255.255.255.0',
            'no shutdown',
            'exit'
        ]
    
        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',
            'exit'
        ]
    
        acl_config = [
            'ip access-list extended MY_ACL',
            'permit ip 192.168.56.130 0.0.0.0 any', # 精确匹配主机
            'deny ip any any',
            'exit'
        ]
    
        all_configs = loopback_config + interface_config + ospf_config + acl_config
    
        logging.info('Sending configuration commands...')
        try:
            output = net_connect.send_config_set(all_configs)
            print("\n--- Configuration Output ---\n", output)
            logging.info('Configuration commands sent successfully.')
        except Exception as e:
            logging.error(f'Error sending configuration commands: {e}')
            raise # 重新抛出异常,以便主函数捕获
    
    def main():
        host = '192.168.56.101' # 请替换为您的Cisco路由器IP地址
        username = input('Please enter your username: ')
        password = getpass.getpass('Please enter your password: ')
        secret = getpass.getpass('Please enter your enable secret: ') # enable密码
    
        # 允许用户选择连接类型,但SSH更推荐
        choice = input('Would you like to connect by using telnet or ssh? (ssh/telnet): ').lower()
        if choice == 'telnet':
            device_type = 'cisco_ios_telnet'
            port = 23
        elif choice == 'ssh':
            device_type = 'cisco_ios'
            port = 22
        else:
            logging.error('Invalid choice. Defaulting to SSH.')
            device_type = 'cisco_ios'
            port = 22
    
        device = {
            'device_type': device_type,
            'host': host,
            'username': username,
            'password': password,
            'secret': secret,
            'port': port,
            'timeout': 100, # 增加超时时间以应对网络延迟或复杂配置
        }
    
        try:
            # 使用with语句确保连接自动关闭
            with ConnectHandler(**device) as net_connect:
                logging.info('Connection established to device.')
    
                # 发送配置命令
                configure_device(net_connect)
    
                # 获取并保存运行配置
                logging.info('Retrieving running configuration...')
                running_configuration = net_connect.send_command('show running-config')
                if running_configuration:
                    remote_config_file_name = f'{host}_running_config.txt'
                    save_config_to_file(running_configuration, remote_config_file_name)
                    logging.info(f'Running configuration saved to {remote_config_file_name}')
    
                    # 尝试加载本地基线配置进行比较
                    local_config_file_name = 'baseline_config.txt' # 假设存在一个基线配置文件
                    try:
                        with open(local_config_file_name, 'r') as local_config_file:
                            local_config = local_config_file.read()
    
                        logging.info('Comparing running configuration with local baseline...')
                        show_differences(local_config, running_configuration, 'Local Baseline', 'Running Config')
    
                    except FileNotFoundError:
                        logging.warning(f'Local baseline configuration file ({local_config_file_name}) not found. Skipping comparison.')
                    except Exception as e:
                        logging.error(f'Error reading local baseline configuration: {e}')
                else:
                    logging.error('Failed to retrieve running configuration from device.')
    
        except Exception as e:
            logging.error(f'An error occurred during device interaction: {e}')
        finally:
            logging.info('The connection process has concluded.')
    
    if __name__ == "__main__":
        main()
    

    总结

    通过Netmiko库自动化Cisco路由器的配置是一个强大且高效的工具。掌握其核心机制,如自动处理配置模式、正确使用send_config_set()和send_command()方法,以及利用with语句管理连接,是编写健壮自动化脚本的关键。同时,结合日志记录、错误处理、配置保存与比较等最佳实践,可以大大提高网络管理的效率和可靠性。始终确保在生产环境中运行自动化脚本前,在测试环境中进行充分的验证。

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发
    相关文章 更多
    Modern Web Guidance 的 legacy-scan 反转建议应该怎样判断?
    Modern Web Guidance 的 legacy-scan 反转建议应该怎样判断?

    说明源码提交对字符串、生成器和数组的识别边界,以及扫描命令与发行包核验限制。

    Codex 0.170.0 正式版的语音与连接更新,适用范围有哪些限制?
    Codex 0.170.0 正式版的语音与连接更新,适用范围有哪些限制?

    0.170.0 的语音更新限于终端通话协商能力的明确新增,同名工具服务器跨环境支持仍标注实验性质;连接部分则修复大请求回退、认证竞态和云端重连等具体问题。这份正式版公告不足以证明所有账户、所有客户端都已具备完整语音功能。

    Hy4 flash 三种权重怎么选,安装和授权要注意哪些条件?
    Hy4 flash 三种权重怎么选,安装和授权要注意哪些条件?

    了解Hy4 flash、FP8与base的适用任务,阅读官方安装及图文代码,并核对资源和MaaS许可条件。

    OpenAI Python SDK 3.55.0 升级看点:Live MCP 服务配置与预算接口变化
    OpenAI Python SDK 3.55.0 升级看点:Live MCP 服务配置与预算接口变化

    OpenAI Python SDK 3.55.0 升级看点:Live MCP 服务配置与预算接口变化。说明已核实的更新范围、类型兼容性和本地版本确认方法。

    OpenAI Java SDK 4.108.0 的两项新增能力适合哪些项目?
    OpenAI Java SDK 4.108.0 的两项新增能力适合哪些项目?

    OpenAI Java SDK 4.108.0 面向 Live MCP 工具接入与 Managed Agents 预算状态处理,说明新增模型、事件含义、正式发布范围和适用限制。

    Free Claude Code 6.19.37 如何兼顾网页搜索与普通工具调用?
    Free Claude Code 6.19.37 如何兼顾网页搜索与普通工具调用?

    Free Claude Code 6.19.37 在自动搜索时保留客户端工具及选择条件,代理执行搜索后仍返回普通调用。说明适用场景、历史信息保留、请求约束与第三方项目的版本边界。

    Google GenAI Go SDK 1.78.0 的 v1beta 配置优先级怎样判断?
    Google GenAI Go SDK 1.78.0 的 v1beta 配置优先级怎样判断?

    Google GenAI Go SDK 1.78.0 将 Gemini Developer API 默认改为 v1,可用 HTTPOptions.APIVersion 或环境变量保留 v1beta,Vertex AI 默认值不变。

    Google GenAI SDK 3.5.0实时交互值得哪些项目升级评估?
    Google GenAI SDK 3.5.0实时交互值得哪些项目升级评估?

    解释实验性实时支持、环境检查与生产评估中需要验证的条件。

    EGM Lite 为什么不会在生成检查清单后自动执行?
    EGM Lite 为什么不会在生成检查清单后自动执行?

    围绕 EGM Lite Stage 2 的仓库实现说明五步职责、人工执行门槛、独立审查条件及已分发包的证据边界。

    Open Code Review 1.13.12 的部分失败与字节边界该怎样评估?
    Open Code Review 1.13.12 的部分失败与字节边界该怎样评估?

    Open Code Review 1.13.12 的升级评估应同时关注退出状态、覆盖缺口与文件读取截断边界。

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版
    macOS

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版
    Windows

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。