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

如何用Python将CSV中IP格式化注入Ubuntu的.conf文件并替换配置?

解决方案:解析IP并替换配置文件内容

Python完全可以实现这个需求,以下是完整的分步实现方案:

1. 解析CSV获取IP列表

基于你现有的代码,需要处理CSV第一行中可能存在的空字符串(由多余空格导致),提取有效IP:

import csv

# 读取CSV文件,提取第一行的IP列表
with open("ip.csv", 'r', encoding='utf-8-sig') as infile:
    reader = csv.reader(infile, delimiter=" ")
    ip_list = next(reader)
    # 过滤空字符串,保留有效IP
    ip_list = [ip.strip() for ip in ip_list if ip.strip()]

2. 格式化IP为目标格式

将每个IP转换为"IP:161"的形式,再拼接成符合配置要求的字符串:

# 格式化每个IP,添加端口和双引号
formatted_ips = [f'"{ip}:161"' for ip in ip_list]
# 拼接成agents配置需要的格式
agents_line = '    agents ["{}"]'.format(','.join(formatted_ips))

3. 替换routers.conf的第二行

读取配置文件的所有行,替换第二行(注意Python列表索引从0开始,第二行对应索引1),然后写回文件:

# 读取配置文件内容
with open("routers.conf", 'r', encoding='utf-8') as conf_file:
    conf_lines = conf_file.readlines()

# 替换第二行的agents配置(确保原文件第二行是agents项)
if len(conf_lines) >= 2:
    conf_lines[1] = agents_line + '\n'  # 保留换行符

# 将修改后的内容写回文件
with open("routers.conf", 'w', encoding='utf-8') as conf_file:
    conf_file.writelines(conf_lines)

完整代码整合

把以上步骤整合为一个完整脚本,方便直接运行:

import csv

def update_agents_config():
    # 1. 读取CSV获取IP列表
    with open("ip.csv", 'r', encoding='utf-8-sig') as infile:
        reader = csv.reader(infile, delimiter=" ")
        ip_list = next(reader)
        ip_list = [ip.strip() for ip in ip_list if ip.strip()]
    
    # 2. 格式化IP
    formatted_ips = [f'"{ip}:161"' for ip in ip_list]
    agents_line = '    agents ["{}"]'.format(','.join(formatted_ips))
    
    # 3. 替换配置文件第二行
    with open("routers.conf", 'r', encoding='utf-8') as conf_file:
        conf_lines = conf_file.readlines()
    
    if len(conf_lines) >= 2:
        conf_lines[1] = agents_line + '\n'
    
    with open("routers.conf", 'w', encoding='utf-8') as conf_file:
        conf_file.writelines(conf_lines)

if __name__ == "__main__":
    update_agents_config()

补充说明

  • 确保routers.conf的第二行确实是agents配置项,如果位置有变动,需要调整代码中conf_lines[1]的索引值。
  • 可以配合Ubuntu的cron定时任务,实现每晚自动执行脚本:
    1. 执行crontab -e编辑定时任务
    2. 添加一行:0 0 * * * /usr/bin/python3 /path/to/your/script.py(每天凌晨0点执行)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 10:33:38