雲梯等 VPN 服務提供大量伺服器節點,Linux NetworkManager 不支援批量匯入。本文展示 Python 腳本:讀取伺服器列表、Jinja2 風格模板渲染、自動生成 UUID、設定權限 600、寫入 /etc/NetworkManager/system-connections/,一鍵完成數十個 VPN 設定。
tpl.cfg
[connection]
id=%(id)s
uuid=%(uuid)s
type=vpn
permissions=user:greatghoul:;
autoconnect=false
[vpn]
service-type=org.freedesktop.NetworkManager.pptp
gateway=%(gateway)s
require-mppe=yes
user=greatghoul
refuse-chap=yes
refuse-eap=yes
password-flags=1
refuse-pap=yes
[ipv4]
method=auto
dns=8.8.8.8;8.8.4.4;
ignore-auto-dns=true
import os, uuid
VPN_SERVERS = [
{'id': 'yunti.pptp.a', 'gateway': 'a.example.com'},
{'id': 'yunti.pptp.b', 'gateway': 'b.example.com'},
{'id': 'yunti.pptp.c', 'gateway': 'c.example.com'},
]
CFG_DIR = '/etc/NetworkManager/system-connections'
CURRENT_DIR = os.path.dirname(__file__)
def add_connection(tpl, conn_info):
filename = os.path.join(CFG_DIR, conn_info['id'])
print('Creating file:', filename)
with open(filename, 'w') as f:
f.write(tpl % conn_info)
os.chmod(filename, 0o600) # 必須 600,否則 NetworkManager 忽略
def create_all():
tpl = open(os.path.join(CURRENT_DIR, 'tpl.cfg')).read()
print('Creating yunti connection files under', CFG_DIR)
for conn_info in VPN_SERVERS:
conn_info.update(uuid=str(uuid.uuid1()))
add_connection(tpl, conn_info)
if __name__ == '__main__':
# 先清理舊檔
for f in os.listdir(CFG_DIR):
if f.startswith('yunti.pptp.'):
os.remove(os.path.join(CFG_DIR, f))
create_all()
$ sudo python create_yunti_config.py
Cleaning up yunti connection files...
Creating yunti connection files under /etc/NetworkManager/system-connections
Creating file: /etc/NetworkManager/system-connections/yunti.pptp.a
Creating file: /etc/NetworkManager/system-connections/yunti.pptp.b
Creating file: /etc/NetworkManager/system-connections/yunti.pptp.c
NetworkManager 會自動重讀配置,網路選單即出現三組 VPN,可隨時切換。
uuid.uuid1():基於 MAC + 時間生成,極低衝突率。connection.id:NetworkManager 修改連線時會重命名檔案為 id,保持一致避免混亂。os.chmod(..., 0o600):檔案必須屬於 root:0600,否則被視為不安全而忽略。password-flags=1:密碼由 keyring/代理程式提供,不存明文。service-type 與 [vpn] 區塊參數。nmcli 驗證導入:nmcli connection load filename。click CLI 工具,支援 --provider、--dry-run 參數。以代碼管理基礎設施配置(Infrastructure as Code),讓重複性網路設定變得可版控、可審計、可複現,是運維自動化的核心思想。