Ho uno script perl che, quando distillata un po ', si presenta così:Verificando un tunnel SSH è installato e funzionante
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
Il fatto è che l'obiettivo $ ip è su un link con molto imprevedibile larghezza di banda, quindi il tunnel potrebbe venire subito, potrebbe volerci un po ', potrebbe non arrivare affatto. Quindi un sonno è necessario per dare al tunnel un po 'di tempo per alzarsi e correre.
Quindi la domanda è: come posso verificare se il tunnel è attivo e funzionante? 10 secondi è un ritardo davvero indesiderato se il tunnel si alza subito. Idealmente, vorrei verificare se è attivo e continuare a creare l'oggetto telnet una volta, per un massimo di, ad esempio, 30 secondi.
Edit: Ping non mi aiuta Mouch, come la fine remota del tunnel è generalmente alto, ma con una quantità molto elevata di packetloss
risolto: Estrapolando dalla punta suggerito da mikebabcock , sleep 10
è stato sostituito con questo blocco, che funziona come un fascino:
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);
}
Dato che stai usando il modulo 'Net :: Telnet', hai provato a usare la chiamata' open' e testare per il successo? Non sono un esperto di Telnet, ma è quello che probabilmente proverò se fossi io ... –
Potrei farlo se non c'è un modo semplice di test: riprova fino al successo se time_spend_trying <30 secondi – Jarmund