Last active
January 10, 2023 11:03
-
-
Save FATESAIKOU/e26569a7efb007c17be722d1ed519b12 to your computer and use it in GitHub Desktop.
my autossh
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
#!/usr/bin/env bash | |
PORT=$1 | |
AUTOSSH_CMD="ssh -Nf -D$PORT [email protected]" | |
# SSH clean up function | |
function stopNfSSHs() { | |
pids=( $(ps -ef | grep '[s]sh -Nf' | awk '{print $2}') ) | |
if [ "${#pids[@]}" -gt 0 ]; then | |
echo "Tunnel stop ${pids[@]}" | |
kill -9 "${pids[@]}" | |
fi | |
} | |
# Signal handler | |
trap 'stopNfSSHs && exit 0' 2 | |
# Clean Up SSH tunnels | |
stopNfSSHs | |
# main logic | |
$AUTOSSH_CMD | |
while true | |
do | |
curl ifconfig.me --connect-timeout 1 --proxy socks4://localhost:$PORT 1>/dev/null 2>&1 | |
res=$? | |
if [ $res -ne 0 ] | |
then | |
echo "[$(date)] Connectivity test failed, clean up connection" | |
stopNfSSHs | |
echo "[$(date)] Reconnecting..." | |
$AUTOSSH_CMD | |
echo "[$(date)] Reconnect complete" | |
else | |
echo "[$(date)] Connected!" | |
fi | |
sleep 1 | |
done | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment