Tuesday, July 23, 2013

SSH Persistent Connection Script

I just reinstalled a test machine and forgot to save my ssh tunnel script so i decided to write a new one.

#!/bin/bash
#this script will constantly maintain (via crontab) a remote forward connection to another machine. This can
#be used as a way to connect to a jumpbox to get over a pesky NAT

remote_listen_port=2222
local_ssh_port=22
remote_host=example.com
remote_user=user1
identity_file=/home/user1/.ssh/key1

connect_string="ssh -N -T -R ${remote_listen_port}:localhost:${local_ssh_port} ${remote_user}@${remote_host} -i ${identity_file} -o ConnectTimeout=60 ServerAliveInterval=10"

process_is_up(){
 ps aux | grep "${connect_string}" | grep -v grep
}

start_bot(){
 ${connect_string}
}


if process_is_up ; then
 echo process is up, exiting
 exit 1
else
 echo process is down, starting now
 start_bot &
fi;
#add to root homedir and then crontab with the following line:
#* * * * * /root/ssh-bot-script.sh > /dev/null

No comments:

Post a Comment