python批量配置交换机简单实现
交换机实现批配置
各交换机的连接IP地址:是192.168.1.1到192.168.1.100
登录凭据:用户名admin,密码Huawei@123
需求:为所有交换机配置VLAN10,名称为“Management”,并将所有端口设为接入模式。
# 导入Netmiko库
from netmiko import ConnectHandler# 生成100台交换机的IP地址,放在一个列表switches里面给下面语句中的的for循环调用
switches = [f"192.168.1.{i}" for i in range(1, 101)]# 用列表形式定义要执行的配置命令
config_commands = ["vlan 10", # 创建VLAN 10"name Management", # 命名VLAN"exit", # 退出VLAN配置模式"interface range gigabitEthernet 1/0/1 - 24", # 选择所有端口"switchport mode access", # 设置为接入模式"switchport access vlan 10", # 绑定到VLAN 10"exit" # 退出接口模式
]# 登录凭据
username = "admin"
password = "Huawei@123"# 循环配置每台交换机
for switch in switches:# 字典形式定义设备登陆的信息device = {"device_type": "cisco_ios", # 设备类型为Cisco IOS"ip": switches, # 交换机IP"username": username, # 用户名"password": password, # 密码}try:# 建立SSH连接net_connect = ConnectHandler(**device)# 发送配置命令output = net_connect.send_config_set(config_commands)# 打印配置结果print(f"配置 {switches} 成功!输出如下:\n{output}")# 保存配置net_connect.save_config()# 断开连接net_connect.disconnect()except Exception as e:# 出错时打印错误信息print(f"配置 {switches} 失败!错误:{e}")如果要验证刚才的配置,把上面for中的output换成下面
output = net_connect.send_command("show vlan brief")
print(f"{switch} VLAN配置:\n{output}")