Skip to content

Instantly share code, notes, and snippets.

@Potat0000
Last active January 23, 2023 06:25
Show Gist options
  • Save Potat0000/d3bdac324ac4d134329693768d3ec0b0 to your computer and use it in GitHub Desktop.
Save Potat0000/d3bdac324ac4d134329693768d3ec0b0 to your computer and use it in GitHub Desktop.
WireGuard Port Change
#!/usr/bin/env python3
# coding=utf-8
import shlex
import subprocess
IFACE_LIST = ['wg_port1', 'wg_port2', 'wg_port3']
def simple_run(command, timeout=3):
try:
output = (
subprocess.check_output(shlex.split(command), timeout=timeout, stderr=subprocess.STDOUT)
.decode("utf-8")
.strip()
)
except subprocess.CalledProcessError as e:
output = e.output.decode("utf-8").strip()
return output
def gen_next(old, base=30000):
return (21 * (old - base) + 1) % 65537 % 2000 + base
for iface in IFACE_LIST:
with open(f'/etc/wireguard/{iface}.conf', 'r') as f:
raw = f.read()
raw = raw.split('\n')
for line_no, line in enumerate(raw):
if line.startswith('ListenPort'):
old = int(line.split('=')[1].strip())
new = gen_next(old)
raw[line_no] = f'ListenPort = {new}'
elif line.startswith('Endpoint'):
line = line.split('=')[1].strip()
addr = line[::-1].split(':', 1)[1][::-1].strip()
old = int(line[::-1].split(':', 1)[0][::-1].strip())
new = gen_next(old)
raw[line_no] = f'Endpoint = {addr}:{new}'
with open(f'/etc/wireguard/{iface}.conf', 'w') as f:
f.write('\n'.join(raw))
simple_run(f"systemctl restart wg-quick@{iface}")
# Required Policy: read, write
local ifaceList {"wg-port-1"; "wg-port-2"; "wg-port-3"}
local Rand do={
local base 30000
return ( ((21 * ($old - $base) + 1) % 65537) % 2000 + $base )
}
foreach iface in=$ifaceList do={
local OldLocal [/interface/wireguard/get $iface listen-port ]
local OldPeer [/interface/wireguard/peers/get [find interface=$iface] endpoint-port ]
local NewLocal [ $Rand old=$OldLocal ]
local NewPeer [ $Rand old=$OldPeer ]
/interface/wireguard/disable $iface
/interface/wireguard/peers/disable [find interface=$iface]
/interface/wireguard/set $iface listen-port=$NewLocal
/interface/wireguard/peers/set [find interface=$iface] endpoint-port=$NewPeer
/interface/wireguard/enable $iface
/interface/wireguard/peers/enable [find interface=$iface]
/log/info "WireGuard Port Changed: $iface | Local $OldLocal -> $NewLocal | Peer $OldPeer -> $NewPeer"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment