Skip to content

Instantly share code, notes, and snippets.

@JimDennis
Created Sep 4, 2016
Embed
What would you like to do?
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