Skip to content

Instantly share code, notes, and snippets.

@SoerenBusse
Created June 27, 2020 11:18
Show Gist options
  • Select an option

  • Save SoerenBusse/dc8f118544aaa437c4b0938ad8f39e2f to your computer and use it in GitHub Desktop.

Select an option

Save SoerenBusse/dc8f118544aaa437c4b0938ad8f39e2f to your computer and use it in GitHub Desktop.
Python script for generating wireguard accounts on an EdgeRouter
[Interface]
PrivateKey = %%PrivateKey%%
Address = %%Address%%
MTU = 1300
DNS = <DNS_IP_ADDRESS - CHANGE HERE>
[Peer]
PublicKey = %%ServerPublicKey%%
AllowedIPs = <ALLOWED_IPS - CHANGE HERE>
Endpoint = <SERVER_ADDRESS - CHANGE HERE>
PersistentKeepalive = 25
peer %%ClientPublicKey%% {
allowed-ips %%Address%%
description "%%Description%%"
}
# Attention: Quick and Dirty Python Script ahead
# Please mind unexpected Exceptions
import subprocess
import sys
import os
def execute(command):
return subprocess.check_output(['bash', '-c', command]).decode(sys.stdout.encoding).replace("\n", "")
if len(sys.argv) < 5:
print("Usage: python generate.py <VPNName> <Name> <Address> <Description>")
exit(1)
vpn_name = sys.argv[1]
name = sys.argv[2]
address = sys.argv[3]
description = sys.argv[4]
# Read server key
with open("/config/auth/wg.pub", "r") as server_public_key_file:
server_public_key = server_public_key_file.read().replace("\n", "")
# Create directory
os.mkdir(name)
# Generate private key
client_private_key = execute("/usr/bin/wg genkey | tee {}/wg.key".format(name))
# Generate public key
client_public_key = execute("/usr/bin/wg pubkey < {}/wg.key | tee {}/wg.pub".format(name, name))
# Generate client configuration from template file
with open("template_client.conf", "r") as templateClientFile:
templateClient = templateClientFile.read()
templateClient = templateClient.replace("%%PrivateKey%%", client_private_key)
templateClient = templateClient.replace("%%Address%%", address)
templateClient = templateClient.replace("%%ServerPublicKey%%", server_public_key)
with open("{}/{}.conf".format(name, vpn_name), "w") as client_config:
client_config.write(templateClient)
# Generate Edgerouter Configuration from Template
with open("template_edgerouter.conf", "r") as templateEdgerouterFile:
templateEdgerouter = templateEdgerouterFile.read()
templateEdgerouter = templateEdgerouter.replace("%%ClientPublicKey%%", client_public_key)
templateEdgerouter = templateEdgerouter.replace("%%Address%%", address)
templateEdgerouter = templateEdgerouter.replace("%%Description%%", description)
with open("{}/er.conf".format(name), "w") as er_config:
er_config.write(templateEdgerouter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment