Remote ssh tunnel in background or script?
David Collins
davidcollins001 at gmail.com
Tue Nov 10 18:19:23 UTC 2009
Kevin Kinsey <kdk at daleco.biz> wrote:
> Greetings!
>
> In order to continue to allow them to connect to an outbound
> SMTP box on the LAN, I've done this on their server:
>
> sudo ssh -L thisbox:24:remotebox:52525 me at remotebox
I wrote a script to get around my home firewall, it doesn't do exactly
as you want but that only requires changing the ssh bit. I call it
from cron so it stays alive, if it dies it will re-connect otherwise
it just checks a lock file.
It may be of use
David
-------------- next part --------------
#!/usr/bin/perl
##
## PURPOSE:
## run reverse ssh to work
##
## designed to be run from crontab. creates a lock file so that
## not more than one instance of the process is started
##
use strict;
use warnings;
## user crontab doesn't have permission in /var for lock file
## or for ports below 1024
my $username='username';
my $hostname="hostname";
my $address=$hostname.".somewhere.com";
my $port=$ARGV[0]; #2022;
my $lckfile="/tmp/revssh.${hostname}.pid";
sub start_ssh {
## fork process to start ssh
defined( my $pid=fork ) or die "cannot fork process: $!";
## parent - open lock file with child pid
if($pid) {
print "Starting process: $pid\n";
open(LOCKFILE,">$lckfile") or die "Cannot create lock file: $!";
print LOCKFILE "${pid}";
close(LOCKFILE);
} else {
## child - start ssh process
exec("ssh -qnNCX -R ${port}:localhost:22 ".
"${username}\@${address}")
or die "cannot exec process\n";
}
}
## main
if(! -e $lckfile) {
start_ssh();
} else {
## get running(?) pid from pid file
@ARGV = ($lckfile);my $old_pid = <ARGV>;
my $running = kill 0, $old_pid;
## lock file exists - is process still running?
if ( $running == 1 ) {
die "Process running: $old_pid\n";
} else {
## check lockfile was deleted!
if(! unlink $lckfile) {
die "Lockfile not deleted\n";
}
print "Orphan lock file - Lock file deleted\n\t";
start_ssh();
}
}
More information about the freebsd-questions
mailing list