Thursday, May 03, 2007

How to do reverse port forwarding using cron

Create a script called startrevssh.sh in /usr/local/bin

#!/bin/sh
REMOTE_HOST="10.3.13.50"
LISTEN_PORT=10010
REMOTE_USER="mp-remote"

COMMAND="/usr/bin/ssh -o "ServerAliveCountMax=3" -o "ServerAliveInterval=20" -N -f -R ${LISTEN_PORT}:localhost:22 $REMOTE_USER@$REMOTE_HOST"
pgrep -f -x "$COMMAND" > /dev/null 2>&1 || ($COMMAND && dt=`date "+%Y/%m/%d %H:%M:%S"` && echo "$dt: ssh reverse forwarding restarted." >> /var/log/revssh.out)

remember to make it executable
chmod +x startrevssh.sh


Now add this script to your cron jobs

Edit /etc/crontab

# m h dom mon dow user command
*/2 * * * * root /usr/local/bin/startrevssh.sh
17 * * * * root run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || run-parts --report /etc/cron.daily
47 6 * * 7 root test -x /usr/sbin/anacron || run-parts --report /etc/cron.weekly

Restart cron
/etc/init.d/cron restart

And Voila! You have a new reverse ssh tunnel which will always to running

0 Comments:

Post a Comment

<< Home