Check if the SSH tunnel is working

I have a perl script that, when it is not numerous, looks like this:

my $randport = int(10000 + rand(1000)); # Random port as other scripts like this run at the same time my $localip = '192.168.100.' . ($port - 4000); # Don't ask... backwards compatibility system("ssh -NL $randport:$localip:23 root\@$ip -o ConnectTimeout=60 -i somekey &"); # create the tunnel in the background sleep 10; # Give the tunnel some time to come up # Create the telnet object my $telnet = new Net::Telnet( Timeout => 10, Host => 'localhost', Port => $randport, Telnetmode => 0, Errmode => \&fail, ); # SNIPPED... a bunch of parsing data from $telnet 

The fact is that the target $ ip is located on a link with very unpredictable bandwidth, so the tunnel may appear immediately, it may take some time, it may not occur at all. Thus, sleep is needed to give the tunnel some time to get up and work.

So the question is: how to check if the tunnel is working? 10 seconds is a really unwanted delay if the tunnel appears immediately. Ideally, I would like to check if this happens and continue creating the telnet object, if so, for a maximum of, say, 30 seconds.

Edit: Ping does not help me mouch, since the remote end of the tunnel is usually up, but with a very large number of packets l

Solved: Extrapolating from the prompt suggested by mikebabcock, sleep 10 been replaced by this block, which works like a charm:

 my $starttime = time(); while (1) { # Check for success if (system("nc -dzw10 localhost $randport > /dev/null") == 0) { last } # Check for timeout if (time() > $starttime + 30) { &fail() } # 250ms delay before recheck select (undef, undef, undef, 0.25); } 
+6
source share
3 answers

Use netcat - often nc on Linux systems:

 nc -dvzw10 ${HOSTNAME} 23 

Works for me, with an answer like:

 Connection to ${HOSTNAME} 23 port [tcp/telnet] succeeded! 

It also returns 0 for success and is satisfied with the simple join after which it leaves.

  • -d means do not read anything from the keyboard.
  • -v means be verbose (disable it in script)
  • -z means disconnect after connecting
  • -w10 means wait up to 10 seconds, otherwise refuse
+6
source

You can integrate ping into your ssh server, and if it works fine, the ssh tunnel is up

 # only a ping sample :-D if ! ping -c 1 192.168.101.9 then echo ":-(" else echo ":-)" fi 
0
source

I think fping might be better than regular regular ping, a more friendly script.

fping -t 60000 [your server]

you should try to connect to the server 60 seconds before failure. Something like

 if(fping -t 60000 [your server]) { execute desired code; } else { execute this script again to rerun;; } 

I think you understand, even if the encoding is not real.

0
source

Source: https://habr.com/ru/post/926326/


All Articles