Files
config-ros/main.py

108 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from librouteros import connect, Api
import csv
import ssl
import threading
from steps import *
"""
自动配置 ros 脚本,需要安装 librouteros 库:
```
pip install librouteros
```
配置文件格式为 CSV包含以下字段
- index: 配置索引,【重要】这个 index 用来生成对应 l2tp-out 用户名中的序号,每个节点都是唯一且固定的
- name: 城市名
- code: 城市代码
- gateway: 网关地址
- public: 公网 IP
- mask: 公网子网掩码
- private: 内网 IP
如果需要添加或修改配置项,从 config.*.bak.csv 文件复制配置项到 config.csv 文件中
如果需要修改配置内容,在下面 “配置执行步骤” 部分添加或修改函数调用
"""
threads = []
failed = []
# 配置执行步骤
steps = [
configNet,
configJgAuth,
configJgMixOuts,
configJgScripts,
configJgLogs,
]
def main():
# 加载配置文件
config_data = []
with open("config.csv", "r", encoding="utf-8-sig") as file:
reader = csv.DictReader(file)
for row in reader:
config_data.append(row)
# 多线程执行 ros 配置
for _, config in enumerate(config_data):
thread = threading.Thread(target=start, args=(config,))
thread.start()
threads.append(thread)
# 等待所有线程完成
for thread in threads:
thread.join()
# 输出结果
print("=" * 20)
print(
"配置完成统计({}/{}), 失败项:{}".format(
len(config_data) - len(failed), len(config_data), len(failed)
)
)
for _, (item, err) in enumerate(failed):
print("{},{},{},{}".format(item["public"], item["name"], item["code"], err))
def start(config):
print(
"{}: 配置{}({})".format(
str(config["index"]).zfill(3), config["name"], config["code"]
)
)
# 连接到 ros
conn: Api
try:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.load_verify_locations(f'certs/{config["cert"]}')
conn = connect(
username="admin",
password="wyongk9815",
host=config["public"],
port=8729,
ssl_wrapper=ctx.wrap_socket,
)
except Exception as err:
failed.append((config, f"连接失败: {err}"))
return
# 配置 ros
try:
for step in steps:
step(conn, config)
except Exception as err:
failed.append((config, f"配置失败: {err}"))
# 关闭连接
conn.close()
main()