You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用字典结合for循环实现Napalm根据IP地址为多台网络设备加载对应配置文件

Solution: Map IPs to Config Files with a Dictionary in Napalm Script

Perfect choice using a dictionary for this mapping—it's clean and scalable. Let's adjust your script to implement this properly:

Corrected Script

from napalm import get_network_driver

# Replace the list with your IP-to-config dictionary
devicelist = {'10.255.32.1': 'device1.cfg', '10.255.32.5': 'device2.cfg'}

# Iterate over both IP address and corresponding config file using .items()
for ip_address, config_file in devicelist.items():
    print(f"Connecting to {ip_address}")
    driver = get_network_driver('ios')
    iosv = driver(ip_address, 'admin', 'password')
    iosv.open()
    
    # Use the config_file variable from the dictionary instead of hardcoding
    iosv.load_merge_candidate(filename=config_file)
    
    diffs = iosv.compare_config()
    if len(diffs) > 0:
        print(diffs)
        iosv.commit_config()
    else:
        print('No changes required.')
    iosv.discard_config()
    iosv.close()

Key Changes Explained

  • Updated devicelist: Swapped the list of IPs for your dictionary that maps each IP to its specific config file. This keeps all your device-config mappings in one easy-to-maintain place.
  • Modified loop: Used devicelist.items() to iterate over both the IP address (ip_address) and its associated config filename (config_file) in each loop iteration.
  • Dynamic config file: Replaced the hardcoded 'device1.cfg' with the config_file variable. Now each device gets its correct config file based on its IP.

This approach is scalable too—adding a new device just means adding a new key-value pair to the devicelist dictionary, no need to tweak the rest of the script logic.

内容的提问来源于stack exchange,提问作者Chuck Slayton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:42:29