Ping (ICMP) Host Monitor Script

This is a script written in PHP that will monitor an IP via ICMP and report via syslog if the system goes down and also reports how long it was down once it comes back up. I needed this to monitor not only my internet connection at home but also my hosted connection and server. It generates the ping itself (in this version) so it requires root access but it would be easy to write a new ping() routine to just call /bin/ping. It runs either as a daemon or at the console but I recommend it as a daemon.

PHP has to be compiled with --enable-pcntl and --enable-sockets.

While I would still call this script beta, it does it's job. Note, that you can send the process a HUP to re-read the configuration without restarting it. Enjoy!

pinger config

#debug
daemonize
monitor host.domain.com
monitor 192.168.1.100

pinger script
#!/usr/local/bin/php
<?php

// Requires PHP 5
declare(ticks 1);
require_once 
'Console/Getopt.php';

$monitored = array();
$pidfile "/tmp/pinger.pid";
$pidwritten false;
$configfile "/etc/pinger.conf";

$pname basename($argv[0]);
if(!
$pname$pname "pinger";


/*
 *
 * Read and setup config values
 *
 */
function read_config()
{
    global 
$configfile;
    global 
$debug;
    global 
$daemon;
    global 
$pidfile;

    
$debug false;
    
$daemon false;

    if(!
file_exists($configfile))
    {
        
fwrite(STDERRsprintf("Could not open config file '%s'\n"$configfile));
        exit(-
1);
    }

    
monitor_host('clearhosts'); // reset the monitor list

    
$config fopen($configfile"r");
    while(!
feof($config))
    {
        
$value '';
        
$line rtrim(fgets($config));
        if(
$line == "") continue;
        
$result explode(" "$line2);
        if(
count($result) == 2)
            list(
$key$value) = $result;
        else
            
$key $result[0];
        if(
$key[0] == '#') continue;

        switch(
$key)
        {
            case 
'daemonize'$daemon true; break;
            case 
'debug'$debug true; break;
            case 
'pidfile'$pidfile $value; break;
            case 
'monitor'monitor_host($value); break;
        }

        if(
$debugprintf("config line %s=%s\n"$key$value);

    }
}


/*
 *
 * Creates a ping - requires root
 *
 */

function ping($host) {
    
$package "\x08\x00\x19\x2f\x00\x00\x00\x00\x70\x69\x6e\x67";

    
/* create the socket, the last '1' denotes ICMP */
    
$socket socket_create(AF_INETSOCK_RAW1);

    if(!
is_bool($socket))
    {
        
/* set socket receive timeout to 1 second */
        
socket_set_option($socketSOL_SOCKETSO_RCVTIMEO, array("sec" => 1"usec" => 0));
    
        
/* connect to socket */
        
socket_connect($socket$hostnull);

        
/* record start time */
        
list($start_usec$start_sec) = explode(" "microtime());
        
$start_time = ((float) $start_usec + (float) $start_sec);

        
socket_send($socket$packagestrlen($package), 0);

        if(@
socket_read($socket255)) 
        {
            list(
$end_usec$end_sec) = explode(" "microtime());
            
$end_time = ((float) $end_usec + (float) $end_sec);

            
$total_time $end_time $start_time;

            return 
$total_time;
        } else {
            return 
false;
        }
    }

    
socket_close($socket);
}

/*
 *
 * Manages adding a host to the monitor list
 *
 */
function monitor_host($host)
{
    global 
$monitored;
    global 
$debug;

    if(
$host == "clearhosts")
    {
        
$monitored = array();
        return;
    }

    if(
preg_match("/^\d*\.\d*\.\d*\.\d*$/"$host))
    {
        
$monitored[$host] = array(
            
"last" => time(),
            
"status" => true,
        );
    } 
    else 
    {
        
$ip gethostbyname($host);
        if(
$host == $ip)
        {
            
fwrite(STDERRsprintf("Error: cannot monitor %s!\n"$host));
            return;
        }

        if(
$debugprintf("Adding %s (%s) to monitor.\n"$host$ip);

        
$monitored[$host] = array(
            
"last" => time(),
            
"status" => true,
        );
    }

}

/*
 *
 * Signal handler routine
 *
 */

function handle_signal($signal)
{
    global 
$pidfile;
    global 
$daemon;

    switch(
$signal)
    {
        case 
SIGTERM
            if(!
$daemon) exit;
            
unlink($pidfile);
            exit;
            break;
        case 
SIGHUP
            if(!
$daemon) return;
            
read_config();        
            break;
        default: break;
    }
}

/*
 *
 * Displays the configuration - for debugging
 *
 */
function show_config()
{
    global 
$daemon;
    global 
$pidfile;
    global 
$monitored;
    
printf("daemon: %s\n", ($daemon)?'true':'false');
    
printf("pidfile: %s\n"$pidfile);
    
printf("monitored:\n");
    
print_r($monitored);
}



/*
 *
 * Start of the main routine
 *
 */
// Get command line options
$args Console_Getopt::readPHPArgv();
$short_opts "dp::c::";
$long_opts = array(
    
"debug",
    
"config=",
);
$options Console_Getopt::getOpt($args$short_opts$long_opts);

if (
PEAR::isError($options)) 
{
    
fwrite(STDERR$options->getMessage() . "\n");
    return 
4;


foreach(
$options[0] as $opt)
{
    list(
$key$value) = $opt;
    switch(
$key)
    {
        case 
'd'$debug true; break;
        case 
'--debug'$debug true; break;
        case 
'c'$configfile $value; break;
        case 
'--config'$configfile $value; break;
    }
}

// Install signal handlers
pcntl_signal(SIGHUP"handle_signal");
pcntl_signal(SIGTERM"handle_signal");

// Process config file
read_config();
if(
$debugshow_config();

// Time to form and write a pid

if($daemon)
{
    
$pid pcntl_fork();
    if(
$pid == -1)
    {
        
fwrite(STDERR"Failed to fork!\n");
        return 
1;
    }
    if(
$pid)
    {
        
$pf fopen($pidfile"w");
        if(
$pf === false)
        {
            
fwrite(STDERRsprintf("Error: cannot write to pidfile: %s\n"$pidfile));
            exit(
5);
        } else {
            
$pidwritten true;
            
fwrite($pf$pid);
            
fclose($pf);
        }
        return 
0;
    }
}

openlog($pnameLOG_NDELAY LOG_PIDLOG_LOCAL0);

while(
true)
{
    if(
$debugprint_r($monitored);
    foreach(
$monitored as $key => $value)
    {
        
$res = (ping($key))?true:false;

        if(
$res != $monitored[$key]['status'])
        {
        if(
$res == false)
        {

            if(!
$debugsyslog(LOG_NOTICEsprintf("lost communication with %s at %s"$keydate("g:i a m-d-Y"time())));
            else 
printf("lost communication with %s at %s\n"$keydate("g:i a m-d-Y"time()));

            } else {

            if(!
$debugsyslog(LOG_NOTICEsprintf("restored communication with %s at %s (%ds)"$keydate("g:i a m-d-Y"time()),
                     
time() - $monitored[$key]['last']));
            else 
printf("restored communication with %s at %s (%ds)\n"$keydate("g:i a m-d-Y"time()),
                     
time() - $monitored[$key]['last']);

            }
            
$monitored[$key]['status'] = $res;
            
$monitored[$key]['last'] = time();
        }
    }
    
sleep(5);
}


if(
$pidwrittenunlink($pidfile);


?>