Skip to content

Instantly share code, notes, and snippets.

@bagustris
Last active April 16, 2026 07:42
Show Gist options
  • Select an option

  • Save bagustris/7074d9caf2b607085d4c082a300bd8d2 to your computer and use it in GitHub Desktop.

Select an option

Save bagustris/7074d9caf2b607085d4c082a300bd8d2 to your computer and use it in GitHub Desktop.
#!/bin/bash
# VPN connect script - fixes stale connections after WiFi change
# Usage: ./vpn.sh
# Please change OVPN_CONFIG and VPN_PASS
OVPN_CONFIG="./client.ovpn"
OVPN_DIR="$(dirname "$OVPN_CONFIG")"
VPN_PASS="YOUR_VPN_PASSWORD_HERE"
# --- Require sudo upfront and keep it alive ---
sudo -v || { echo "sudo required"; exit 1; }
echo "==> Killing existing OpenVPN processes..."
sudo killall -q openvpn 2>/dev/null
sleep 1
# Force kill if still alive
sudo killall -9 -q openvpn 2>/dev/null
echo "==> Cleaning up stale tun interfaces..."
for tun in $(ip -o link show type tun 2>/dev/null | awk -F: '{print $2}' | tr -d ' '); do
sudo ip link set "$tun" down 2>/dev/null
sudo ip link delete "$tun" 2>/dev/null
done
echo "==> Flushing routes and DNS cache..."
sudo ip route flush cache 2>/dev/null
sudo resolvectl flush-caches 2>/dev/null
echo "==> Restarting network services..."
sudo systemctl restart systemd-resolved
sudo nmcli networking off
sleep 1
sudo nmcli networking on
# Wait for WiFi to reconnect
echo "==> Waiting for network..."
for i in $(seq 1 15); do
if nmcli -t -f STATE general 2>/dev/null | grep -q "connected"; then
echo " Network ready."
break
fi
sleep 1
done
# Verify DNS works before connecting
echo "==> Verifying DNS resolution..."
for i in $(seq 1 5); do
if host mandara-vpn.naist.jp >/dev/null 2>&1; then
echo " DNS OK."
break
fi
if [ "$i" -eq 5 ]; then
echo " WARNING: DNS not resolving, trying anyway..."
fi
sleep 1
done
echo "==> Connecting to VPN..."
cd "$OVPN_DIR"
echo "$VPN_PASS" | sudo openvpn --config "$OVPN_CONFIG" --askpass /dev/stdin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment