修改文本文件

修改 VPN_WireGuard连接方式的配置文件

文件格式: .conf

下载下来的源文件内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
'''
#
# Use this configuration with WireGuard client
#
[Interface]
Address = 10.14.0.2/16
PrivateKey = <insert_your_private_key_here>
DNS = 162.252.172.57, 149.154.159.92
[Peer]
PublicKey = OoFY46j/w4uQFyFu/OQ/h3x+ymJ1DJ4UR1fwGNxOxk0=
AllowedIPs = 0.0.0.0/0
Endpoint = 103.176.152.200:51820
'''
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import os, re

def modify_wireguard_config():
'''
修改VPN_WireGuard连接方式的配置文件。
读取源文件,同时创建新文件
遍历源文件的行,用re.sub(old_word,new_word,str) ,同时逐行写入新文件。
删除源文件,更名新文件名为源文件名
'''
fd = r"C:\Users\xiaoyx\Downloads"
files = [f"{fd}\{i}" for i in os.listdir(fd) if re.search(r'.conf$', i)]
w1 = '<insert_your_private_key_here>'
w2 = 'mKTo/XWQemHxEDJxfDaNvcFwB4R42WQDtV7ZURUitWg='
for file in files:
with open(file, 'r',
encoding='utf-8') as file1, open(f'{file}.bak',
'w',
encoding='utf-8') as file2:
for line in file1:
file2.write(re.sub(w1, w2, line))
os.remove(file)
os.rename(f'{file}.bak', file)


if __name__ =='__main__':
modify_wireguard_config()