Skip to content

Instantly share code, notes, and snippets.

@ayufan
Last active October 13, 2024 12:07
Show Gist options
  • Save ayufan/81bf456e3017f465dcd463234c1921c3 to your computer and use it in GitHub Desktop.
Save ayufan/81bf456e3017f465dcd463234c1921c3 to your computer and use it in GitHub Desktop.
OpenWRT script to dynamically assign Wireguard NordVPN host based on closest or country
#!/bin/sh
#set -x
URL="https://api.nordvpn.com/v1/servers/recommendations?&filters\[servers_technologies\]\[identifier\]=wireguard_udp&limit=1"
if [[ -n "$DRY" ]]; then
uci() {
echo "uci: $@"
}
fi
if [[ "$1" == "off" ]]; then
uci set network.wg_nordvpn_peer.public_key=""
uci set network.wg_nordvpn_peer.endpoint_host=""
uci commit network.wg_nordvpn_peer
ifup wg_nordvpn
echo "NordVPN disabled."
exit 0
fi
if [[ -n "$1" ]]; then
if COUNTRY_ID=$(curl -s "https://api.nordvpn.com/v1/servers/countries" | jq -e "[.[] | select(.code == \"$1\" or .name == \"$1\")][0].id"); then
URL="$URL&filters\[country_id\]=$COUNTRY_ID"
else
echo "Failed to find country: $1."
exit 1
fi
fi
if curl -s --fail-with-body -o /tmp/wireguard/nordvpn.json "$URL"; then
if ! HOST=$(jq -e -r '.[]|.hostname' /tmp/wireguard/nordvpn.json); then
echo "No NordVPN hostname found."
exit 1
fi
uci set network.wg_nordvpn_peer.public_key=$(jq -r '(.[]|.technologies|.[].metadata|.[].value)' /tmp/wireguard/nordvpn.json)
uci set network.wg_nordvpn_peer.endpoint_host="$HOST"
if uci changes network.wg_nordvpn_peer | grep "^"; then
uci commit network.wg_nordvpn_peer
ifup wg_nordvpn
echo "New NordVPN peer: $HOST"
else
echo "The NordVPN peer not changed: $HOST"
fi
else
echo "Could not get new NordVPN peer..."
cat /tmp/wireguard/nordvpn.json
exit 1
fi
@ayufan
Copy link
Author

ayufan commented Oct 13, 2024

  1. Write content to nordvpn.sh.
  2. Install jq: opkg update && opkg install jq.
  3. Set chmod +x nordvpn.sh.
  4. Run ./nordvpn.sh to set closest server, or ./nordvpn.sh France or ./nordvpn.sh FR.

The NordVPN Wireguard has to be preconfigured in /etc/config/network:

config interface 'wg_nordvpn'
	option proto 'wireguard'
	option private_key 'NORDVPN-CLIENT-PRIVATE-KEY'
	list addresses '10.5.0.2/32'

config wireguard_wg_nordvpn 'wg_nordvpn_peer'
	option endpoint_port '51820'
	option persistent_keepalive '25'
	option route_allowed_ips '1'
	list allowed_ips '0.0.0.0/0'
	list allowed_ips '::/0'

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