Linux 下 NetworkManager 不支援批量匯入 VPN 設定,手動逐一新增極其繁瑣。本文展示如何編寫 Python 腳本,透過模板引擎批量生成 /etc/NetworkManager/system-connections/ 下的連線設定檔,解決雲梯等多伺服器 VPN 切換痛點。
grep 'example' ~/.config -r
grep 'example' /etc/ -r
定位至 /etc/NetworkManager/system-connections/ 目錄下的各連線檔案。
典型 PPTP VPN 設定檔包含三段:
[connection]
id=yunti.pptp.tw1
uuid=063db9b5-5915-4f3e-8bb4-2fe58abf5be5
type=vpn
permissions=user:greatghoul:;
autoconnect=false
[vpn]
service-type=org.freedesktop.NetworkManager.pptp
gateway=tw1.example.com
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
connection.id:唯一識別名connection.uuid:隨機 UUIDconnection.permissions:目前使用者vpn.gateway:VPN 伺服器位址vpn.user:帳號ipv4.dns:DNS 設定
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'},
]
# 模板 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
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 out:
out.write(tpl % conn_info)
os.chmod(filename, 0600) # 必須 600 權限,屬 root:root
def create_all():
tpl = open(os.path.join(CURRENT_DIR, 'tpl.cfg'), 'r').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)
$ sudo python create_yunti_config.py
Cleaning up yunti connection files...
Removing file: /etc/NetworkManager/system-connections/yunti.pptp.a
...
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
GitHub Gist 完整版 包含清理舊設定、錯誤處理等完善功能。