Skip to content

Instantly share code, notes, and snippets.

@JimDennis
Created September 4, 2016 02:03
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 JimDennis/8b5b108ec6b45edf38c8ffe60162546f to your computer and use it in GitHub Desktop.
Save JimDennis/8b5b108ec6b45edf38c8ffe60162546f to your computer and use it in GitHub Desktop.
SSH Reverse shell with handling for killing "stale" instances and restarting tunnels if they die or get killed
#!/usr/bin/bash
# Start ssh reverse shell tunnel; but also poll and restart as necessary
# checks for previously running tunnel and kills it if found
# Enhancement to: http://www.thegeekstuff.com/2013/11/reverse-ssh-tunnel/
STALEPID=$(ps faxwww | grep '[7]000:localhost:22' | cut -d' ' -f1)
[ -n "$STALEPID" ] && {
echo 'Killing previous (stale?) tunnel' >&2
kill "$STALEPID"
kill -0 "$STALEPID" && kill -9 "$STALEPID"
}
while :; do
ssh -fN -R 7000:localhost:22 "$user@$pubhost" || {
echo 'Unable to establish tunnel' >&2
sleep 10
continue
}
PID=$(ps faxwww | grep '[7]000:localhost:22' | cut -d' ' -f1) || {
echo "Unable to find tunnel process $PID" >&2
sleep 5
continue
}
while sleep 30; do #
kill -0 "$PID" || break
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment