首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 批量生成 NetworkManager VPN 配置腳本實戰

     編輯:更多程式設計知識

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:隨機 UUID
  • connection.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)

關鍵細節

  • 檔名與 id 一致:NetworkManager 修改連線時會依 id 重命名檔案
  • 權限 600 + root:root:否則 NetworkManager 會忽略該設定檔
  • 需 sudo 執行:寫入系統目錄需要根權限

執行結果


$ 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 完整版 包含清理舊設定、錯誤處理等完善功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved