Skip to content

Instantly share code, notes, and snippets.

@AfroThundr3007730
Created June 17, 2022 00:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AfroThundr3007730/9822086ca060e6c79f56aef0c843fca4 to your computer and use it in GitHub Desktop.
Save AfroThundr3007730/9822086ca060e6c79f56aef0c843fca4 to your computer and use it in GitHub Desktop.
Wrapper and service to start and stop wireguard interfaces
#!/bin/bash
# Wrapper to start and stop wireguard interfaces
wg_start() {
echo "Setting up Wireguard interface $2..."
ipv4=$(awk '$1 ~ /Address/ && $3 ~ /\./ {print $3}' /etc/wireguard/"${2}".conf)
ipv6=$(awk '$1 ~ /Address/ && $3 ~ /:/ {print $3}' /etc/wireguard/"${2}".conf)
ip link add dev "$2" type wireguard
[[ -n $ipv4 ]] && ip addr add dev "$2" "$ipv4"
[[ -n $ipv6 ]] && ip addr add dev "$2" "$ipv6"
wg setconf "$2" <(wg-quick strip "$2")
ip link set up dev "$2"
}
wg_stop() {
echo "Tearing down Wireguard interface $2..."
ip link set down dev "$2" &> /dev/null
ip link del dev "$2" &> /dev/null
}
[[ $1 == start ]] && wg_start "$@"
[[ $1 == stop ]] && wg_stop "$@"
[[ $1 == restart ]] && wg_stop "$@" && wg_start "$@"
[[ $1 == status ]] && wg show "$2"
exit 0
[Unit]
Description=WireGuard automatic connection for %I
After=network-online.target
Documentation=man:wg(8)
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/sbin/wg-auto start %I
ExecStop=/usr/local/sbin/wg-auto stop %I
ExecReload=/usr/local/sbin/wg-auto restart %I
[Install]
WantedBy=multi-user.target
@AfroThundr3007730
Copy link
Author

Example: systemctl enable --now wg-auto@wg0

This will reuse the address info wg-quick save stores in the WireGuard config. Masquerading is already enabled with firewalld.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment