Skip to content

Instantly share code, notes, and snippets.

Created February 5, 2022 10:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Simple wireguard config generator
#!/usr/bin/env python3
Simple Wireguard config generator
sysctl config:
export PATH=/usr/sbin:$PATH
sysctl net.ipv4.ip_forward=1
sudo apt install resolvconf
from subprocess import Popen, PIPE, STDOUT
from typing import NamedTuple, Optional
class Keypair(NamedTuple):
ip: str
privkey: str
pubkey: str
class Server(NamedTuple):
ip_range: str
port: int
endpoint: str
def gene_keypair(save_name: Optional[str] = None) -> tuple[str, str]:
Generate new keypair
p = Popen(["wg", "genkey"], stdout=PIPE)
privkey = p.stdout.readline()
p = Popen(["wg", "pubkey"], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
pubkey =
translate = lambda x: x.strip().decode()
privkey, pubkey = translate(privkey), translate(pubkey)
if save_name:
with open(f"{save_name}_privkey", "w") as f:
with open(f"{save_name}_pubkey", "w") as f:
return privkey, pubkey
def read_keypair(save_name: str) -> tuple[str, str]:
Read keypair from file
with open(f"{save_name}_privkey", "r") as f:
privkey =
with open(f"{save_name}_pubkey", "r") as f:
pubkey =
return privkey, pubkey
def gene_server_config(
server_keypair: Keypair, server_config: Server, client_keypair: Keypair
) -> str:
Generate server config
return f"""[Interface]
Address = {server_config.ip_range}
ListenPort = {server_config.port}
PrivateKey = {server_keypair.privkey}
PublicKey = {client_keypair.pubkey}
AllowedIPs = {client_keypair.ip}/32"""
def gene_client_config(
server_keypair: Keypair, server_config: Server, client_keypair: Keypair
) -> str:
Generate client config
return f"""[Interface]
Address = {client_keypair.ip}/32
PrivateKey = {client_keypair.privkey}
PublicKey = {server_keypair.pubkey}
Endpoint = {server_config.endpoint}:{server_config.port}
AllowedIPs = {server_config.ip_range}"""
if __name__ == "__main__":
# --- TODO Modify content below to suit you need ---
server_keypair = Keypair("", *read_keypair("server"))
client_keypair = Keypair("", *gene_keypair("client"))
server_config = Server(
ip_range="", port=51820, endpoint=""
# --- Modify contetnt end ---
server_config_file = gene_server_config(
server_keypair, server_config, client_keypair
client_config_file = gene_client_config(
server_keypair, server_config, client_keypair
print("# Server config")
print("# Client config")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment