Ping (ICMP) Monitor Script

This script is from 2004 and mostly obselete. It is here for reference on various functions. There are better ways to do this now.

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!

#debug
daemonize
monitor host.domain.com
monitor 192.168.1.100

 

#!/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(STDERR, sprintf("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(" ", $line, 2);
        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($debug) printf("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_INET, SOCK_RAW, 1);

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

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

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

        if(@socket_read($socket, 255)) 
        {
            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(STDERR, sprintf("Error: cannot monitor %s!\n", $host));
            return;
        }

        if($debug) printf("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($debug) show_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(STDERR, sprintf("Error: cannot write to pidfile: %s\n", $pidfile));
            exit(5);
        } else {
            $pidwritten = true;
            fwrite($pf, $pid);
            fclose($pf);
        }
        return 0;
    }
}

openlog($pname, LOG_NDELAY | LOG_PID, LOG_LOCAL0);

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

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

            if(!$debug) syslog(LOG_NOTICE, sprintf("lost communication with %s at %s", $key, date("g:i a m-d-Y", time())));
            else printf("lost communication with %s at %s\n", $key, date("g:i a m-d-Y", time()));

            } else {

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

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


if($pidwritten) unlink($pidfile);


?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *