Skip to content

Instantly share code, notes, and snippets.

@jezman
Created February 28, 2020 06:07
Show Gist options
  • Save jezman/6314547ebcd64e66ae4d85c4b4b09f7b to your computer and use it in GitHub Desktop.
Save jezman/6314547ebcd64e66ae4d85c4b4b09f7b to your computer and use it in GitHub Desktop.
Add wireguard peer.
#!/bin/bash
if [[ "$EUID" -ne 0 ]]; then
echo "Permission denied"
exit
fi
WG_CONFIG="/etc/wireguard/wg0.conf"
[ -f $WG_CONFIG ] || echo "Wireguard config not found"; exit 86
CLIENT_NAME="$1"
ALLOWED_IPS="$2"
[ "$CLIENT_NAME" == "" ] && read -p "Client name: " -e CLIENT_NAME
[ "$ALLOWED_IPS" == "" ] && read -p "Allowed ips: " -e ALLOWED_IPS
[ "$WG_ENDPOINT" == "" ] && read -p "Public ip: " -e WG_ENDPOINT
CLIENT_PRIVKEY=$( wg genkey )
CLIENT_PUBKEY=$( echo $CLIENT_PRIVKEY | wg pubkey )
SUBNET=$( grep "Address" $WG_CONFIG | awk '{print $3}')
SUBNET_MASK=$( echo $SUBNET | cut -d "/" -f 2 )
SERVER_PUBKEY=$( wg show | grep "public key" | awk '{print $3}' )
LISTENING_PORT=$( wg show | grep "listening port" | awk '{print $3}' )
LASTIP=$( grep "/32" $WG_CONFIG | tail -n1 | awk '{print $3}' | cut -d "/" -f 1 | cut -d "." -f 4 )
CLIENT_ADDRESS="${SUBNET::-4}$((LASTIP+1))"
# Add client to wireguard config
echo "
# $CLIENT_NAME
[Peer]
PublicKey = $CLIENT_PUBKEY
AllowedIPs = $CLIENT_ADDRESS/32" >> $WG_CONFIG
# Generate client config
echo "[Interface]
PrivateKey = $CLIENT_PRIVKEY
Address = $CLIENT_ADDRESS/$SUBNET_MASK
[Peer]
PublicKey = $SERVER_PUBKEY
AllowedIPs = $ALLOWED_IPS/32
Endpoint = $WG_ENDPOINT:$LISTENING_PORT
PersistentKeepalive = 25" > $HOME/$CLIENT_NAME-wg0.conf
qrencode -t ansiutf8 -l L < $HOME/$CLIENT_NAME-wg0.conf
ip address | grep -q wg0 && wg set wg0 peer "$CLIENT_PUBKEY" allowed-ips "$CLIENT_ADDRESS/32"
echo "Configuration file: $HOME/$CLIENT_NAME-wg0.conf"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment