自动运维华为或者思科交换机的python脚本,建议收藏!

360影视 日韩动漫 2025-04-08 18:06 3

摘要:交换机的管理通常涉及通过SSH、Telnet等协议与设备交互,而Python的库能够轻松支持这些协议。此外,Python脚本还可以与现有运维工具(如Ansible、SaltStack)集成,进一步提升自动化程度。对于需要批量管理多台交换机的场景,Python的

交换机的管理通常涉及通过SSH、Telnet等协议与设备交互,而Python的库能够轻松支持这些协议。此外,Python脚本还可以与现有运维工具(如Ansible、SaltStack)集成,进一步提升自动化程度。对于需要批量管理多台交换机的场景,Python的灵活性尤为突出。

在编写Python脚本之前,我们需要做好一些准备工作,包括安装必要的工具和配置交换机。

1.安装Python和相关库

要开始编写脚本,首先需要确保系统中安装了Python(建议使用3.6或更高版本)。接下来,我们需要安装几个常用的网络管理库:

Netmiko:一个支持多厂商设备的SSH客户端库,适用于Cisco、Juniper、Arista等品牌的交换机。Paramiko:一个底层的SSH库,Netmiko基于其开发,适合需要更底层控制的场景。NAPALM:一个高级网络自动化框架,提供设备抽象层,支持多种操作。

安装这些库的方法很简单,在终端运行以下命令:

pip install netmiko paramiko napalm

2.配置交换机

为了让Python脚本能够成功连接到交换机,需要确保以下条件:

启用SSH或Telnet:SSH因其安全性更高而更常用。需要在交换机上启用SSH服务并配置IP地址。创建用户账户:为脚本创建一个具有适当权限的用户名和密码,避免使用默认账户以提升安全性。网络可达性:确保运行脚本的设备与交换机在同一网络中,或通过正确的路由配置能够访问。

例如,在Cisco交换机上启用SSH的配置命令如下:

enableconfigure terminalhostname Switch1ip domain-name example.comcrypto key generate rsausername admin privilege 15 password mypasswordline vty 0 4transport input sshexitip ssh version 2

完成这些配置后,交换机即可通过SSH接受远程连接。

3.编写Python脚本

脚本的基本结构

一个典型的交换机管理脚本通常包括以下几个部分:

导入库:引入必要的Python库,如Netmiko。定义设备信息:包括IP地址、用户名、密码和设备类型。建立连接:通过SSH或Telnet连接到交换机。执行命令:发送命令并获取输出。处理结果:解析输出并进行后续操作。关闭连接:任务完成后断开连接。

基础示例:连接交换机并获取信息

以下是一个使用Netmiko连接到Cisco交换机并执行“show version”命令的简单脚本:

from netmiko import ConnectHandler# 定义设备信息device = { 'device_type': 'cisco_ios', # 设备类型,根据厂商调整 'ip': '192.168.1.1', # 交换机IP地址 'username': 'admin', # 用户名 'password': 'mypassword', # 密码}# 建立连接net_connect = ConnectHandler(**device)# 执行命令并获取输出output = net_connect.send_command('show version')# 打印结果print("交换机版本信息:")print(output)# 关闭连接net_connect.disconnect

运行这段脚本后,你将看到交换机的版本信息输出到终端。这是最基础的自动化任务,展示了与交换机交互的核心步骤。

自动化配置任务

除了获取信息,Python脚本还可以执行复杂的配置任务。例如,批量创建VLAN:

from netmiko import ConnectHandler# 定义设备信息device = { 'device_type': 'cisco_ios', 'ip': '192.168.1.1', 'username': 'admin', 'password': 'mypassword',}# 建立连接net_connect = ConnectHandler(**device)# 定义VLAN列表vlans = [10, 20, 30]# 进入配置模式net_connect.config_mode# 批量创建VLANfor vlan in vlans: commands = [ f'vlan {vlan}', f'name VLAN_{vlan}', 'exit' ] net_connect.send_config_set(commands)# 退出配置模式net_connect.exit_config_mode# 保存配置net_connect.send_command('write memory')# 关闭连接net_connect.disconnectprint("VLAN配置完成并已保存!")

这段脚本会依次创建VLAN 10、20和30,并为每个VLAN命名,最后保存配置到交换机的启动配置文件中。

监控与故障排除

Python脚本还可以用于实时监控交换机状态。例如,检查CPU使用率:

from netmiko import ConnectHandlerimport re# 定义设备信息device = { 'device_type': 'cisco_ios', 'ip': '192.168.1.1', 'username': 'admin', 'password': 'mypassword',}# 建立连接net_connect = ConnectHandler(**device)# 获取CPU使用率output = net_connect.send_command('show processes cpu')# 使用正则表达式提取CPU使用率cpu_usage = re.search(r'CPU utilization for five seconds: (\d+)%', output).group(1)# 打印结果print(f"交换机CPU使用率: {cpu_usage}%")# 关闭连接net_connect.disconnect

这个脚本通过正则表达式从命令输出中提取CPU使用率,适用于需要定期监控设备性能的场景。

4.高级主题

错误处理

在实际应用中,脚本可能会遇到连接超时、认证失败等问题。为提高健壮性,需要添加错误处理机制:

from netmiko import ConnectHandler, NetmikoTimeoutException, NetmikoAuthenticationException# 定义设备信息device = { 'device_type': 'cisco_ios', 'ip': '192.168.1.1', 'username': 'admin', 'password': 'mypassword',}try: # 尝试连接 net_connect = ConnectHandler(**device) output = net_connect.send_command('show version') print(output) net_connect.disconnectexcept NetmikoTimeoutException: print("错误:连接超时,请检查网络或设备状态")except NetmikoAuthenticationException: print("错误:认证失败,请检查用户名和密码")except Exception as e: print(f"未知错误: {e}")

通过try-except块,脚本可以在发生异常时提供清晰的反馈,而不会直接崩溃。

日志记录

为了便于调试和审计,建议为脚本添加日志记录功能。Python的logging模块非常适合这个需求:

import loggingfrom netmiko import ConnectHandler# 配置日志logging.basicConfig( filename='switch_automation.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')# 定义设备信息device = { 'device_type': 'cisco_ios', 'ip': '192.168.1.1', 'username': 'admin', 'password': 'mypassword',}try: logging.info("尝试连接到交换机") net_connect = ConnectHandler(**device) logging.info("连接成功") output = net_connect.send_command('show version') logging.info(f"命令输出: {output}") net_connect.disconnect logging.info("连接已关闭")except Exception as e: logging.error(f"发生错误: {e}") print(f"发生错误,请查看日志文件: {e}")

运行后,所有的操作和错误都会记录到switch_automation.log文件中,方便后续分析。

性能优化

当管理大量交换机时,脚本的性能至关重要。以下是几种优化方法:

并发执行:使用Python的threading或multiprocessing模块并行处理多台设备。例如: from netmiko import ConnectHandlerfrom concurrent.futures import ThreadPoolExecutor# 定义多个设备devices = [ {'device_type': 'cisco_ios', 'ip': '192.168.1.1', 'username': 'admin', 'password': 'mypassword'}, {'device_type': 'cisco_ios', 'ip': '192.168.1.2', 'username': 'admin', 'password': 'mypassword'},]def manage_device(device): net_connect = ConnectHandler(**device) output = net_connect.send_command('show version') net_connect.disconnect return f"{device['ip']} 输出: {output}"# 使用线程池并行执行with ThreadPoolExecutor(max_workers=2) as executor: results = executor.map(manage_device, devices)# 打印结果for result in results: print(result)缓存连接:对同一设备执行多个命令时,避免重复建立连接。批量操作:将多条命令合并为一个配置集,减少交互次数。

5.华为交换机完整脚本

此脚本适用于华为交换机(如AR系列或S系列),实现以下功能:

连接到华为交换机。获取设备版本信息(display version)。创建VLAN并命名。备份当前配置到本地文件。添加错误处理和日志记录。

脚本代码

import loggingfrom netmiko import ConnectHandler, NetmikoTimeoutException, NetmikoAuthenticationExceptionimport datetimeimport os# 配置日志logging.basicConfig( filename='huawei_switch_automation.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')# 定义华为交换机信息huawei_switch = { 'device_type': 'huawei', # Netmiko支持的华为设备类型 'ip': '192.168.1.10', # 交换机IP地址 'username': 'admin', # 用户名 'password': 'Huawei@123', # 密码 'port': 22, # SSH端口,默认22}# VLAN配置参数vlans_to_create = [ {'id': 10, 'name': 'VLAN_10'}, {'id': 20, 'name': 'VLAN_20'}]# 备份文件路径backup_dir = 'huawei_config_backups'os.makedirs(backup_dir, exist_ok=True)def connect_to_huawei_switch: """连接到华为交换机并执行任务""" try: logging.info(f"尝试连接到交换机 {huawei_switch['ip']}") connection = ConnectHandler(**huawei_switch) logging.info("连接成功") # 获取版本信息 version_output = connection.send_command('display version') print("交换机版本信息:") print(version_output) logging.info(f"版本信息: {version_output}") # 创建VLAN for vlan in vlans_to_create: commands = [ f'vlan {vlan["id"]}', f'name {vlan["name"]}', 'quit' ] config_output = connection.send_config_set(commands) logging.info(f"创建VLAN {vlan['id']} 成功: {config_output}") print(f"VLAN {vlan['id']} 创建成功") # 备份配置 config_output = connection.send_command('display current-configuration') timestamp = datetime.datetime.now.strftime('%Y%m%d_%H%M%S') backup_file = f"{backup_dir}/huawei_config_{huawei_switch['ip']}_{timestamp}.txt" with open(backup_file, 'w') as f: f.write(config_output) logging.info(f"配置已备份到 {backup_file}") print(f"配置已备份到 {backup_file}") # 关闭连接 connection.disconnect logging.info("连接已关闭") except NetmikoTimeoutException: error_msg = "连接超时,请检查网络或设备状态" logging.error(error_msg) print(error_msg) except NetmikoAuthenticationException: error_msg = "认证失败,请检查用户名和密码" logging.error(error_msg) print(error_msg) except Exception as e: error_msg = f"发生未知错误: {e}" logging.error(error_msg) print(error_msg)if __name__ == "__main__": connect_to_huawei_switch

使用说明

准备工作:确保已安装Netmiko(pip install netmiko),并在交换机上启用SSH。修改参数:根据实际环境修改huawei_switch中的IP地址、用户名和密码。运行脚本:执行脚本后,脚本会连接交换机,获取版本信息,创建指定VLAN,并将配置备份到本地文件夹。日志:所有操作和错误会记录到huawei_switch_automation.log文件中。

6.思科交换机完整脚本

此脚本适用于思科交换机(如Catalyst系列),实现以下功能:

连接到思科交换机。获取设备版本信息(show version)。创建VLAN并命名。备份运行配置到本地文件。添加错误处理和日志记录。

脚本代码

import loggingfrom netmiko import ConnectHandler, NetmikoTimeoutException, NetmikoAuthenticationExceptionimport datetimeimport os# 配置日志logging.basicConfig( filename='cisco_switch_automation.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')# 定义思科交换机信息cisco_switch = { 'device_type': 'cisco_ios', # Netmiko支持的思科IOS设备类型 'ip': '192.168.1.1', # 交换机IP地址 'username': 'admin', # 用户名 'password': 'Cisco@123', # 密码 'secret': 'enable123', # 启用密码(如果需要) 'port': 22, # SSH端口,默认22}# VLAN配置参数vlans_to_create = [ {'id': 10, 'name': 'VLAN_10'}, {'id': 20, 'name': 'VLAN_20'}]# 备份文件路径backup_dir = 'cisco_config_backups'os.makedirs(backup_dir, exist_ok=True)def connect_to_cisco_switch: """连接到思科交换机并执行任务""" try: logging.info(f"尝试连接到交换机 {cisco_switch['ip']}") connection = ConnectHandler(**cisco_switch) logging.info("连接成功") # 进入启用模式(如果需要) connection.enable # 获取版本信息 version_output = connection.send_command('show version') print("交换机版本信息:") print(version_output) logging.info(f"版本信息: {version_output}") # 创建VLAN connection.config_mode # 进入配置模式 for vlan in vlans_to_create: commands = [ f'vlan {vlan["id"]}', f'name {vlan["name"]}', 'exit' ] config_output = connection.send_config_set(commands) logging.info(f"创建VLAN {vlan['id']} 成功: {config_output}") print(f"VLAN {vlan['id']} 创建成功") # 保存配置 connection.send_command('write memory') logging.info("配置已保存到启动配置文件") # 备份配置 config_output = connection.send_command('show running-config') timestamp = datetime.datetime.now.strftime('%Y%m%d_%H%M%S') backup_file = f"{backup_dir}/cisco_config_{cisco_switch['ip']}_{timestamp}.txt" with open(backup_file, 'w') as f: f.write(config_output) logging.info(f"配置已备份到 {backup_file}") print(f"配置已备份到 {backup_file}") # 关闭连接 connection.disconnect logging.info("连接已关闭") except NetmikoTimeoutException: error_msg = "连接超时,请检查网络或设备状态" logging.error(error_msg) print(error_msg) except NetmikoAuthenticationException: error_msg = "认证失败,请检查用户名和密码" logging.error(error_msg) print(error_msg) except Exception as e: error_msg = f"发生未知错误: {e}" logging.error(error_msg) print(error_msg)if __name__ == "__main__": connect_to_cisco_switch

使用说明

准备工作:确保已安装Netmiko(pip install netmiko),并在交换机上启用SSH。修改参数:根据实际环境修改cisco_switch中的IP地址、用户名、密码和启用密码(如果有)。运行脚本:执行脚本后,脚本会连接交换机,获取版本信息,创建指定VLAN,保存配置并备份到本地文件夹。日志:所有操作和错误会记录到cisco_switch_automation.log文件中。

7.华为与思科脚本的差异

设备类型:华为使用device_type: 'huawei'。思科使用device_type: 'cisco_ios'。命令语法:华为使用display命令(如display version、display current-configuration),VLAN配置无需进入全局配置模式。思科使用show命令(如show version、show running-config),需要进入配置模式(config t)并保存配置(write memory)。启用模式:华为通常不需要额外的启用密码。思科可能需要启用密码(secret字段),并通过connection.enable进入特权模式。

运行环境要求

Python版本:建议使用Python 3.6或更高版本。依赖库:安装Netmiko(pip install netmiko)。网络配置:确保交换机已启用SSH,且运行脚本的设备与交换机网络可达。

扩展建议

多设备支持:将设备信息存储在列表或文件中,循环处理多台交换机。并发执行:使用ThreadPoolExecutor实现多线程,提升大规模网络的处理效率。更多功能:添加接口状态检查、日志分析等功能。

这些脚本是完整且可运行的示例,你可以根据实际需求调整参数或功能。希望对你有所帮助!

来源:网络技术联盟站

相关推荐