Skip to content

Instantly share code, notes, and snippets.

@chenx6
Created February 5, 2022 10:49
Show Gist options
  • Save chenx6/327188985eed797c33293da16387763d to your computer and use it in GitHub Desktop.
Save chenx6/327188985eed797c33293da16387763d to your computer and use it in GitHub Desktop.
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
resolveconf:
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)
p.stdin.write(privkey)
p.stdin.close()
pubkey = p.stdout.read()
translate = lambda x: x.strip().decode()
privkey, pubkey = translate(privkey), translate(pubkey)
if save_name:
with open(f"{save_name}_privkey", "w") as f:
f.write(privkey)
with open(f"{save_name}_pubkey", "w") as f:
f.write(pubkey)
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 = f.read()
with open(f"{save_name}_pubkey", "r") as f:
pubkey = f.read()
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}
[Peer]
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}
[Peer]
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("192.168.1.1", *read_keypair("server"))
client_keypair = Keypair("192.168.1.3", *gene_keypair("client"))
server_config = Server(
ip_range="192.168.1.1/24", port=51820, endpoint="1.1.1.1"
)
# --- 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(server_config_file)
print("# Client config")
print(client_config_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment