修改或创建wireguard的配置文件

WireGuard连接方式的配置文件

下载下来的源文件上这样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
'''
#
# 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
'''
# 下载的文件需要修改PrivateKey = my_key
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
28
29
30
31
32
#_python3@windows _#
#_date:2023-12-17_#
#_修改wireguard应用的配置文件_#
#_encoding = utf-8_#

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()
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#_python3@linux _#
#_date:2023-12-17_#
#_encoding = utf-8_#
#_修改wireguard应用的配置文件_#
#-----------------------------------------------

import os, re, stat


def writing_wg0_conf(base):
ext = '.conf'
filename = base + ext
downfold = '/home/xiaoyx/下载'
downfile = os.path.join(downfold, filename)
dct = {}
with open(downfile, 'r', encoding='utf-8') as file:
rows = file.readlines()
for row in rows:
if '=' in row:
ls = row.split(' = ', 1)
dct.update({ls[0]: re.sub('\n', '', ls[1])})
rows1 = ['[Interface]\n', 'ListenPort = 49852\n']
rows2 = ['[Peer]\n', 'PersistentKeepalive = 25\n']
wd1 = '<insert_your_private_key_here>'
wd2 = 'mKTo/XWQemHxEDJxfDaNvcFwB4R42WQDtV7ZURUitWg='
for k, v in dct.items():
str = k + ' = ' + v + '\n'
if k in ['Address', 'PrivateKey', 'DNS']:
str = re.sub(wd1, wd2, str)
rows1.append(str)
else:
rows2.append(str)
rows = rows1 + rows2
with open(r'/etc/wireguard/wg0.conf', 'w', encoding='utf-8') as f:
f.writelines(rows)

if __name__ == "__main__":
base = input('输⼊下载的配置⽂件名,如 uk-man')
writing_wg0_conf(base)