Skip to content

Instantly share code, notes, and snippets.

@numpde
Created February 25, 2024 15:23
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 numpde/a473d01b77ab5b9f016a7ff9b6765c90 to your computer and use it in GitHub Desktop.
Save numpde/a473d01b77ab5b9f016a7ff9b6765c90 to your computer and use it in GitHub Desktop.
ETHZ VPN (with OTP/MFA)
#!/bin/bash
# This script connects to ETH Zurich via `openconnect`
# using the `oathtool` to generate the OTP (of MFA's fame).
# Attempts to reconnect if the connection appears broken.
# Run as:
# bash ethz-vpn.sh
LOGIN_NAME="*************@student-net.ethz.ch"
GENERAL_PASSWORD='************'
OTP_SECRET="******************************"
CHECK_IP="google.com" # ideally, an ETHZ-internal IP address
start_vpn() {
echo "Attempting to start VPN..." > /dev/tty
(echo $GENERAL_PASSWORD; oathtool -b --totp $OTP_SECRET; sleep 1) | sudo openconnect -u $LOGIN_NAME --useragent=AnyConnect -g student-net sslvpn.ethz.ch --passwd-on-stdin &
VPN_PID=$!
sleep 10
echo "VPN started. PID: $VPN_PID" > /dev/tty
}
check_vpn() {
fail_count=0
while true; do
if ! ping -c 1 $CHECK_IP > /dev/null 2>&1; then
((fail_count++))
echo "Ping attempt failed $fail_count time(s)." > /dev/tty
if [ $fail_count -ge 5 ]; then
echo "VPN connection appears to be down. Attempting to reconnect..." > /dev/tty
notify-send "VPN Connection" "VPN is down. Attempting to reconnect..." -t 2000
sudo kill $VPN_PID
return 1
fi
else
if [ $fail_count -gt 0 ]; then
echo "VPN connection restored." > /dev/tty
fi
fail_count=0
fi
sleep 4
done
}
while true; do
start_vpn
if check_vpn; then
notify-send "VPN Connection" "VPN reconnection in 5 seconds..." -t 2000
echo "Reconnecting in 5 seconds..." > /dev/tty
sleep 5
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment