实用脚本能批量OSPF吗?

wen 实用脚本 55

本文目录导读:

实用脚本能批量OSPF吗?

  1. 方案一:利用Excel + Python(最通用,推荐)
  2. 方案二:使用Ansible(运维标准方案)
  3. 方案三:纯脚本 & Expect(适合一次性或简单场景)
  4. 需要特别注意的坑(实用建议)
  5. 总结推荐

针对“批量配置OSPF”的需求,通常分为批量启用OSPF批量配置OSPF策略(如修改Cost、Network、区域等),以下是几个实用且经过验证的脚本方案,适用于不同厂商设备。

利用Excel + Python(最通用,推荐)

适用于网络设备数量多、需要精确控制每个接口配置的场景。

思路: 用Excel维护设备列表和接口OSPF参数,通过Python脚本批量下发。

准备Excel文件 (ospf_config.xlsx)

Device_IP OSPF_Process Area Interface Network_Prefix Cost Auth_Key
0.0.1 1 0 GigabitEthernet0/0 0.0.0/30 10 cisco123
0.0.1 1 10 GigabitEthernet0/1 16.1.0/24 - -
0.0.2 1 0 GigabitEthernet0/0 0.0.4/30 5 cisco123

Python脚本 (使用Netmiko)

import netmiko
import pandas as pd
from netmiko import ConnectHandler
import getpass
# 读取Excel
df = pd.read_excel('ospf_config.xlsx')
# 去重获取设备列表
devices = df['Device_IP'].unique()
# 登录凭证(建议使用环境变量或Keyring)
username = input("Enter SSH username: ")
password = getpass.getpass("Enter SSH password: ")
# 遍历每台设备
for device_ip in devices:
    device_config = {
        'device_type': 'cisco_ios',  # 根据实际设备修改
        'host': device_ip,
        'username': username,
        'password': password,
        'port': 22,  # 或 830 (NETCONF)
    }
    # 获取该设备的所有配置行
    device_rows = df[df['Device_IP'] == device_ip]
    try:
        conn = ConnectHandler(**device_config)
        conn.enable()  # 进入特权模式
        config_commands = []
        for _, row in device_rows.iterrows():
            intf = row['Interface']
            ospf_proc = int(row['OSPF_Process'])
            area = int(row['Area'])
            prefix = row['Network_Prefix']
            cost = row['Cost']
            auth_key = row['Auth_Key']
            # 构建接口配置命令
            config_commands.append(f"interface {intf}")
            if pd.notna(cost):
                config_commands.append(f"ip ospf cost {int(cost)}")
            if pd.notna(auth_key):
                # 简单认证示例(MD5更复杂)
                config_commands.append(f"ip ospf authentication-key {auth_key}")
            # 启用OSPF
            config_commands.append("ip ospf {ospf_proc} area {area}".format(ospf_proc=ospf_proc, area=area))
        # 发送全部配置
        output = conn.send_config_set(config_commands)
        print(f"✅ {device_ip} OSPF配置完成。")
        # 可选:保存配置
        # conn.save_config()
        conn.disconnect()
    except Exception as e:
        print(f"❌ {device_ip} 失败: {e}")
print("批量配置结束。")

使用Ansible(运维标准方案)

适用于已有Ansible基础设施、需要合规审计的场景。

Ansible Playbook (ospf_bulk.yml)

---
- name: 批量配置OSPF
  hosts: network_devices
  gather_facts: no
  vars:
    ospf_config:
      - { interface: "GigabitEthernet0/0", process: 1, area: 0, prefix: "10.0.0.0 0.0.0.3" }
      - { interface: "GigabitEthernet0/1", process: 1, area: 10, prefix: "172.16.1.0 0.0.0.255" }
  tasks:
    - name: 配置接口OSPF参数
      ios_config:
        parents: "interface {{ item.interface }}"
        lines:
          - "ip ospf {{ item.process }} area {{ item.area }}"
      loop: "{{ ospf_config }}"

执行命令

ansible-playbook ospf_bulk.yml -i inventory.txt --ask-vault-pass

纯脚本 & Expect(适合一次性或简单场景)

如果只有几台设备、配置逻辑简单(如所有接口加入area0),可用TCL/Expect脚本。

Shell/Expect脚本示例 (ospf_bulk.exp)

#!/usr/bin/expect
set user "admin"
set pass "cisco"
set enable_pass "cisco123"
# 从文件读取设备IP
set f [open "devices.txt" r]
while {[gets $f ip] != -1} {
    spawn ssh $user@$ip
    expect "Password:"
    send "$pass\r"
    expect ">"
    send "enable\r"
    expect "#"
    send "configure terminal\r"
    expect "(config)#"
    # 将所有接口加入OSPF area 0(适用于简单场景)
    send "interface GigabitEthernet0/0\r"
    expect "(config-if)#"
    send "ip ospf 1 area 0\r"
    expect "(config-if)#"
    send "interface GigabitEthernet0/1\r"
    expect "(config-if)#"
    send "ip ospf 1 area 0\r"
    expect "(config-if)#"
    send "end\r"
    expect "#"
    send "write memory\r"
    expect "#"
    send "exit\r"
    close
}
close $f

需要特别注意的坑(实用建议)

  1. network命令 vs ip ospf命令

    • 老式设备router ospf 1network 10.0.0.0 0.0.0.3 area 0
    • 新式设备:建议在接口下直接执行 ip ospf 1 area 0,更精确、不易出错。
    • 脚本中建议统一使用接口模式,避免wildcard-mask写错。
  2. 配置回滚

    • 批量前,先用 show running-config | include ospf 备份。
    • Python脚本中可增加 conn.send_command('show run | include ospf') 并保存到文件。
  3. 认证处理

    OSPF认证密码在脚本中不要硬编码,推荐使用环境变量、Hashicorp Vault或Ansible Vault。

  4. 设备差异

    • 华为ospf 1area 0.0.0.0network 10.0.0.0 0.0.0.3(wildcard mask)
    • Juniperset interfaces ge-0/0/0 unit 0 family inet address 10.0.0.1/30set protocols ospf area 0 interface ge-0/0/0.0
    • 如果厂商混杂,需要在device_type上做条件判断。

总结推荐

场景 推荐方案
一次性批量配置50台以下 方案一(Python + Excel)
企业级、持续运维、合规 方案二(Ansible)
只有4-5台、纯文本操作 方案三(Expect)
已有CMDB(Excel/数据库) 方案一(最灵活,可扩展)

建议:先拿1台设备测试脚本,确保show ip ospf neighbor能看到邻居建立成功,再全量执行。

抱歉,评论功能暂时关闭!