5 =head1 NAME $RCSfile: tunnel.pl,v $
7 Set up a tunnel for emailing
15 Andrew DeFaria <Andrew@ClearSCM.com>
23 Wed 19 Aug 2020 09:09:09 AM MST
33 Usage: tunnel.pl [-u|sage] [-h|elp] [-ve|rbose] [-d|ebug]
37 -u|sage: Displays this usage
38 -h|elp: Display full help
40 -d|ebug: Output debug messages
41 -host1: First host for tunnel (Default: localhost)
42 -port1: Port for host1
43 -host2: Second host for tunnel (Default: defaria.com)
44 -port2: Port for host2
45 -a|nnounce: Whether to announce startup (Default false)
46 -maxtretries: Maximum number of retry attempt to reestablish tunnel
48 -nodaemon: Whether to go into daemon mode (Default: Daemon mode)
52 This script sets up an SSH tunnel for the purposes of emailing.
59 use File::Temp qw(tempfile);
63 use POSIX ':sys_wait_h';
65 use lib "$FindBin::Bin/../lib";
74 my $VERSION = '$Revision: 1.0 $';
75 ($VERSION) = ($VERSION =~ /\$Revision: (.*) /);
78 usage => sub { pod2usage },
79 help => sub { pod2usage (-verbose => 2)},
80 verbose => sub { set_verbose },
81 debug => sub { set_debug },
84 host2 => 'defaria.com',
86 remotehost => 'defaria.com',
99 $log->err($msg, $err);
108 Report "Tunnel killed unexpectedly", 1;
110 kill 'INT', $ssh->get_master_pid;
116 my $tunnelStr = "-NL$opts{host1}:$opts{port1}:$opts{host2}:$opts{port2}";
118 my $retryattempts = 0;
121 my ($fh, $filename) = tempfile;
123 my $ssh = Net::OpenSSH->new(
125 master_opts => $tunnelStr,
126 default_stderr_file => $filename
129 Report("Unable to establish ssh tunnel " . $ssh->error, 1) if $ssh->error;
131 # Check to see if address is already in use
138 if (grep /address already in use/i, @lines) {
139 Report 'Unable to start tunnel - Address already in use', 1;
141 my $msg = 'Ssh tunnel ';
142 $msg .= $retryattempts ? 'reestablished' : 'established';
144 speak $msg, $log if $opts{announce};
148 # Reset retry attempts since we reestablished the tunnel
149 $retryattempts = 0 if $retryattempts;
151 # Wait for master to exit
152 waitpid($ssh->get_master_pid, WUNTRACED);
154 Report("Ssh tunnel terminated unexpectedly - Maximum retry count hit ($opts{maxretries}) - giving up", 1)
155 if $retryattempts++ >= $opts{maxretries};
157 $opts{announce} = $retryattempts;
159 Report 'Ssh tunnel terminated unexpectedly - Attempting restart';
185 # Turn off daemon mode if we are in the Perl debugger;
186 no warnings; # Ignore warning about used only once $DB::OUT when not in debugger
187 $opts{daemon} = 0 if defined $DB::OUT;
192 name => "$Logger::me",
193 timestamped => 'yes',
197 $log->msg("$FindBin::Script v$VERSION");
199 $SIG{INT} = $SIG{TERM} = \&interrupt;
201 EnterDaemonMode if $opts{daemon};