#!/usr/bin/perl -w
use Net::Ping;
$file = "/var/log/demone.log"; ## nome del File Log Specificare la path
$t = 0; ## contatore
$sec_delay=60; ## delay prima del check gateway
@hosts = ('192.168.99.40', '212.239.81.25'); ## hosts da controllare aggiungere quanti ne volete
#unlink $file;
$GW_1= "192.168.99.243"; ## Primo GW (default)
$GW_2= "192.168.99.242" ; ## Gateway Alternativo
######## Funzione per il controllo del GW attualmente utilizzato
sub change_gateway
{
$route_tmp = `route`;
@array = split (/ /,$route_tmp);
$default_GW = "$array[134]";
sleep 1;
system(`/etc/rc.d/rc.inet1 stop`);
sleep 1;
system(`/etc/rc.d/rc.inet1 `);
sleep 1;
system(`route delete default`);
sleep 1;
if ($default_GW eq $GW_1)
{
system(`route add default gw $GW_2`);
printf " ENTRO 1 \n";
}
if ($default_GW eq $GW_2)
{
system(`route add default gw $GW_1`);
printf " ENTRO 2 \n";
}
}
######## Funzione PING
sub ping
{
$n_host = $#hosts;
$ris = 0;
for ($i = 0; $i <= $n_host;$i++)
{
$p = Net::Ping->new("icmp");
$flag_ping=$p->ping("$hosts[$i]");
if ("$flag_ping" eq 0){$ris = $ris + 1;};
if ("$flag_ping" eq 1){$ris = 0;};
$p->close();
}
if ($ris == 0){$ris=1;}
else {$ris=0;}
return $ris;
}
################ CORE PROCESS ######################
while (1)
{
$date = localtime; ## Prendo la data del giorno
sleep 1; ## Delay di un secondo
$t=$t+1;
if ($t % $sec_delay == 0) ## Razionalizzazione del tempo
{
if (ping() == 1)
{ ## HOST IS UP NESSUN CAMBIO
$res_ping="OK is UP";
open (FILE, ">>$file") || die ("non posso aprire il file");
print FILE "$date | host di riferimento=@hosts -> $res_ping Nessun Cambio \n";
close (FILE);
};
if (ping() == 0)
{ ## HOST IS DOWN CAMBIO GW !!
open (FILE, ">>$file") || die ("non posso aprire il file");
$res_ping="CRITICAL is DOWN";
change_gateway();
print FILE "$date | host di riferimento=@hosts -> $res_ping Cambio GW \n";
close (FILE);
};
};
};
exit 0