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";
73 my $VERSION = '$Revision: 1.0 $';
74 ($VERSION) = ($VERSION =~ /\$Revision: (.*) /);
77 usage => sub { pod2usage },
78 help => sub { pod2usage (-verbose => 2)},
79 verbose => sub { set_verbose },
80 debug => sub { set_debug },
83 host2 => 'defaria.com',
85 remotehost => 'defaria.com',
95 if (-f "$FindBin::Bin/shh") {
96 $log->msg("Not speaking because we were asked to be quiet - $msg");
101 my ($status, @output) = Execute "/usr/local/bin/gt \"$msg\"";
103 $log->err("Unable to speak (Status: $status) - "
104 . join ("\n", @output), $status) if $status;
110 my ($msg, $err) = @_;
115 $log->err($msg, $err);
124 Report "Tunnel killed unexpectedly", 1;
126 kill 'INT', $ssh->get_master_pid;
132 my $tunnelStr = "-NL$opts{host1}:$opts{port1}:$opts{host2}:$opts{port2}";
134 my $retryattempts = 0;
137 my ($fh, $filename) = tempfile;
139 my $ssh = Net::OpenSSH->new(
141 master_opts => $tunnelStr,
142 default_stderr_file => $filename
145 Report("Unable to establish ssh tunnel " . $ssh->error, 1) if $ssh->error;
147 # Check to see if address is already in use
154 if (grep /address already in use/i, @lines) {
155 Report 'Unable to start tunnel - Address already in use', 1;
157 my $msg = 'Ssh tunnel ';
158 $msg .= $retryattempts ? 'reestablished' : 'established';
160 Say $msg if $opts{announce};
164 # Reset retry attempts since we reestablished the tunnel
165 $retryattempts = 0 if $retryattempts;
167 # Wait for master to exit
168 waitpid($ssh->get_master_pid, WUNTRACED);
170 Report("Ssh tunnel terminated unexpectedly - Maximum retry count hit ($opts{maxretries}) - giving up", 1)
171 if $retryattempts++ >= $opts{maxretries};
173 $opts{announce} = $retryattempts;
175 Report 'Ssh tunnel terminated unexpectedly - Attempting restart';
201 # Turn off daemon mode if we are in the Perl debugger;
202 no warnings; # Ignore warning about used only once $DB::OUT when not in debugger
203 $opts{daemon} = 0 if defined $DB::OUT;
208 name => "$Logger::me",
209 timestamped => 'yes',
213 $log->msg("$FindBin::Script v$VERSION");
215 $SIG{INT} = $SIG{TERM} = \&interrupt;
217 EnterDaemonMode if $opts{daemon};