Last active
November 17, 2015 12:58
-
-
Save royvandam/a1190180dc758046c267 to your computer and use it in GitHub Desktop.
AutoSSH
This file contains 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
#!/bin/bash | |
# Default settings | |
hostname=server.example.com | |
port=22 | |
keep_alive_interval=300 | |
keep_alive_count_max=2 | |
backoff=30 | |
user=user | |
id_rsa=/home/user/.ssh/id_rsa | |
pid="" | |
pidfile=/var/run/autossh.pid | |
logfile=/var/log/autossh.log | |
log_to_console=true | |
# Consume configuration file | |
configuration=/etc/default/autossh | |
[ -e $configuration ] && source $configuration | |
### ### ### ### | |
log() { | |
echo "[`date`] $1" >> $logfile | |
if $log_to_console; then | |
echo $1 >&2 | |
fi | |
} | |
# Trap signals | |
trap "on_exit" EXIT | |
trap "on_sigterm" SIGTERM SIGINT | |
on_exit() { | |
[ -e $pidfile ] && rm -f $pidfile | |
} | |
sig_term=false | |
on_sigterm() { | |
[ -n "$pid" ] && kill $pid | |
sig_term=true | |
} | |
### ### ### ### | |
# Check if key file is available | |
if [ ! -e $id_rsa ]; then | |
log "SSH rsa key not installed, aborting." | |
exit 1 | |
fi | |
# Create pid file | |
if ! echo $$ > $pidfile; then | |
log "Failed to create pid file, aborting." | |
exit 1 | |
fi | |
function run_ssh() { | |
ssh -R 0:localhost:22 -p ${port} -T -N \ | |
-o "PasswordAuthentication=no" \ | |
-o "User=${user}" \ | |
-o "IdentityFile=${id_rsa}" \ | |
-o "TCPKeepAlive=yes" \ | |
-o "ServerAliveInterval=${keep_alive_interval}" \ | |
-o "ServerAliveCountMax=${keep_alive_count_max}" \ | |
${hostname} | tee -a ${logfile} 2>&1 | |
return ${PIPESTATUS[0]} | |
} | |
# Run reverse ssh tunnel | |
log "Starting ..." | |
while ! $sig_term; do | |
run_ssh & | |
pid=$! | |
wait $pid | |
log "Stopped with exit code: '$?'" | |
$sig_term && exit 0 | |
log "Restarting autossh after '$backoff' secconds." | |
delay=$backoff | |
while [ $delay -gt 0 ] ; do | |
sleep 1 | |
((delay -= 1)) | |
$sig_term && exit 0 | |
done | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment