Skip to content

Instantly share code, notes, and snippets.

@spede
Last active December 10, 2016 13:30
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 spede/1be831352fbfdf3973ad477778d38afe to your computer and use it in GitHub Desktop.
Save spede/1be831352fbfdf3973ad477778d38afe to your computer and use it in GitHub Desktop.
#! /usr/local/bin/bash
# Cronable port forwarding script for PIA/transmission running on
# FreeNAS
#
# Requires bash, jq (JSON parser) and curl
# pkg install jq bash curl
#
# Your PrivateInternetAccess credentials
PIA_USER=username
PIA_PASS=password
get_new_port( ) {
if ! [ -x $(curl) ]; then
echo "Curl not installed/not executable"
exit 0
fi
# get the local tunnel ip
local_ip=$(ifconfig tun0 | grep "inet " | cut -d\ -f2)
#client_id seems to want random data
client_id=$(head -n 100 /dev/urandom | md5 -r | tr -d " -")
port=$(curl --silent --data "user=$PIA_USER&pass=$PIA_PASS&client_id=$client_id&local_ip=$local_ip" https://www.privateinternetaccess.com/vpninfo/port_forward_assignment | jq .port)
if ! [[ $port =~ ^[0-9]+$ ]]; then
echo "Garbled data: $port"
exit 0
fi
transmission-remote -p $port
}
is_port_forwarded( ) {
# -pt tests for open port.
json=$(transmission-remote -pt)
if [[ $json == "Port is open: No" ]]; then
echo "Closed port detected"
get_new_port
elif [[ $json == "Port is open: Yes" ]]; then
echo "Open port detected"
exit 1
else
echo "Error: transmission said: $json"
exit 0
fi
}
re_check_connectivity( ) {
if nc -zw 1 google.com 80; then
echo "VPN connection restored."
else
echo "Unable to restore VPN connection. Subscription expired? Exiting."
exit 0
fi
}
check_for_connectivity( ) {
if nc -zw 1 google.com 80; then
echo "VPN connection up."
else
echo "VPN connection down. Restarting..."
service openvpn restart
re_check_connectivity
fi
}
check_for_connectivity
is_port_forwarded
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment