Last active
October 13, 2024 12:07
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nordvpn.sh
.jq
:opkg update && opkg install jq
.chmod +x nordvpn.sh
../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
: