#!/usr/bin/php -q
    <?php

    //Creates a check for HTTP and HTTPS services. Also creates a SSL cert check.
    //Every host is scanned for the ports listed below, and if an web service is found, a service check is created for it.

    $database_folder = "/etc/nagios/scripts/auto_generate_database/"; //Folder of the SQLLite databases to use for host lookup.

    $outputfile = "autoconfig_Custom-services.cfg";
    #$outputfile = "/etc/nagios/conf.d/auto_generated/autoconfig_http-services.cfg";

    $check_http = "/etc/nagios/plugins/check_http"; //Location of Nagios check_http command. This command does all the work and the config is bases on what this command returns.

    $servicehttps_ports_array = array("443","8443","9443","18200","18201","18202","18203","18204","18205","18206","18207","18208","18209","18210");// array of ports for SSL/TLS checks. Also creates a cert check for each ones of these.
    $servicehttp_ports_array = array("80","8080","8888");// array of ports for normal HTTP checks
    $httpcodes = "200,301,302,403,404"; //HTTP codes that are OK

    //////////////////////////// MAIN  //////////////////////////// 

    #var_dump($argv);
    #exit();

    include_once("/etc/nagios/scripts/lib/check_for_custom_config_lib.php"); //Load check for custom config library.
    $servicegroups_array = array();// Servicegroup array
    $servicehttp_array = array();// http service array
    $servicehttps_array = array();// https service array

    //Open the database with a list of servers.
    $dbh  = new PDO("sqlite:$database_folder/servers.sqlite3") or die("cannot open the database");

    //Build the arrays
    foreach($servicehttps_ports_array as $port) {
        $servicehttps_array["$port"] = array();
    }
    foreach($servicehttp_ports_array as $port) {
        $servicehttp_array["$port"] = array();
    }




    $stmt = $dbh->query("SELECT * FROM servers;");
    $debug_count = 0;

    if($argc>1)
    {
        echo "Pinging $argv[1]       \r\n";
        //ping to see if the host is up.
        exec("ping -c 1 $argv[1]", $null, $result);
        if (!($result == 0)){ continue;}
        echo "Checking $argv[1] with ISPortal      \r";
        $Output = NagiosServiceCheck($argv[1]);
        echo $Output;
        $fh= fopen($argv[1],'w');
        fwrite($fh, $Output);
        fclose($fh);
    }
    else
    {
        //Loop over the list of servers.
        foreach ($stmt as $row) {

            $host = $row["hostname"];
            $ip = $row["ip"];
            echo "Pinging $host       \r\n";
            //ping to see if the host is up.
            exec("ping -c 1 $ip", $null, $result);
            if (!($result == 0)){ continue;}

            echo "Checking $host with ISPortal      \r";

            #httpChecks($host,$ip); //Check for HTTP and HTTPS ports

            $Output = NagiosServiceCheck($host);

            echo $Output;

            $fh= fopen($host,'w');
            fwrite($fh, $Output);
            fclose($fh);

            $debug_count++;
        #    if ($debug_count > 50) {break 1;} //Stop after X servers for testing
        }
    }

    exit();




    function ServiceCheck($ServiceName) {
        switch ($i) 
        {
            case 0:
                echo "i equals 0";
                break;
            case 1:
                echo "i equals 1";
                break;
            case 2:
                echo "i equals 2";
                break;
        }
    }

    function NagiosServiceCheck($host) 
    {
        try
        {
            #$client = new SoapClient("https://IsPortal/API.asmx?WSDL", array('login' => "EID@FQDN.COM", 'password' => "MyPasswordGoesHere", 'user_agent' => 'PHPSoapClient'));
            $client = new SoapClient("https://IsPortal/API.asmx?WSDL", array('user_agent' => 'PHPSoapClient', 'cache_wsdl' => WSDL_CACHE_NONE));
            #var_dump($client->__getFunctions());
            #$result = $client->HelloWorld()->HelloWorldResult;
            #$result = $client->Testing_HelloWorld()->Testing_HelloWorldResult;
            #$result = $client->Nagios_GenerateCustomServices($host, "true")->Nagios_GenerateCustomServicesResult;
            #$result = $client->__soapCall(Nagios_GenerateCustomServices, 'Hostname' => '$host', 'MustBeSetToAutomatic', => 'True')->Nagios_GenerateCustomServicesResult;
            #$result = $client->Nagios_GenerateCustomServices(new SoapParam('Hostname', $Hostname), new SoapParam("True", $MustBeSetToAutomatic))->Nagios_GenerateCustomServicesResult;
            #$result = $client->Nagios_GenerateCustomServices(array('parameters' => $params))->Nagios_GenerateCustomServicesResult;
            $params = array('Hostname' => $host, 'MustBeSetToAutomatic' => 'True');
            $result = $client->__soapCall('Nagios_GenerateCustomServices', array('parameters' => $params))->Nagios_GenerateCustomServicesResult;
            #echo $result;
            return $result;
        }
        catch (Exception $e)
        {
            echo 'caught execption: ', $e->getMessage(), "\n";
        }
    }

    function httpChecks($host,$ip) {

            global $httpcodes,$check_http,$servicehttp_array,$servicehttps_array,$servicehttps_ports_array,$servicehttp_ports_array;

            //Check for an active HTTP service on an array of ports.
            foreach($servicehttp_ports_array as $port) {

                ///Check for an active HTTP service on an array of ports.
                $output_array = array();
                exec ($check_http." -p $port -H $ip --expect=$httpcodes -t 2", $output_array); //Use the Nagios check_http to probe the ports.
                if( preg_match("/HTTP OK:/",$output_array[0]) ) {
                    echo "HTTP $port found for $host                         \n";
                    array_push($servicehttp_array["$port"], $host); //dump found host and port into array
                    //var_dump($servicehttps_array);
                }
            }


            //Check for an active HTTPS service on an array of ports.
            foreach($servicehttps_ports_array as $port) {

                $output_array = array();
                exec ($check_http." -p $port -H $ip -S --expect=$httpcodes -t 2", $output_array); //Use the Nagios check_http to probe the ports.
                if( preg_match("/HTTP OK:/",$output_array[0]) ) {
                    echo "HTTPS $port found for $host                         \n";
                    array_push($servicehttps_array["$port"], $host); //dump found host and port into array
                    //var_dump($servicehttps_array);
                }
            }
    }

    function generateServiceGroups($servicegroups_array) {

        //Create a service group for each new service monitored.
        $output_group = "";
        $servicegroups_array = array_unique($servicegroups_array);

        foreach($servicegroups_array as $name) {

            echo "servicegroup:$name\n";
            $output_group .= "define servicegroup{\n";
            $output_group .= "      servicegroup_name       $name\n";
            $output_group .= "      alias\n";
            $output_group .= "}\n";
        }
        return($output_group);
    }



    function generateServiceHTTP($servicehttp_array,$servicehttp_ports_array){

        $service_list = "";
        $service = "";
        global $servicegroups_array,$httpcodes;

        //loop over each port.
        foreach($servicehttp_ports_array as $port) {


            $service_list = "";

            if (count($servicehttp_array[$port]) > 0) {
                //loop over the array
                foreach($servicehttp_array[$port] as $host) {

                    //skip if there is a custom config.
                    if (checkForCustomConfig($host,"HTTP $port")) {
                    continue;
                    }

                    //Put additional check here.

                    //Service is good, add it to the list.
                    $service_list .= $host . ",";

                }

                $service_list=substr_replace($service_list,"",-1); //remove ending comma

                $service .="define service{\n";
                $service .="        use                             generic-service\n";
                $service .="        host_name                       $service_list\n";
                $service .="        service_description             HTTP $port\n";
                $service .="        check_command                   check_web! --expect=$httpcodes -p $port -w 8 -c 9\n";
                $service .="        check_interval                  5\n";
                $service .="        flap_detection_enabled          0\n";
                $service .="        retry_interval                  1\n";
                $service .="        notifications_enabled           0\n";
                $service .="        servicegroups                   http-checks-$port\n";
                $service .="        contact_groups                  OpsSysadmin\n";
                $service .="        notes                           HTTP $port Website checks\n";
                $service .="}\n";

                array_push($servicegroups_array,"http-checks-$port");

            }
        }

        return($service);

    }




    function generateServiceHTTPS($servicehttps_array,$servicehttps_ports_array){

        $service_list = "";
        $service = "";
        global $servicegroups_array,$httpcodes;;

        //loop over each port.
        foreach($servicehttps_ports_array as $port) {
            $service_list = "";

            if (count($servicehttps_array[$port]) > 0) {
                //loop over the array
                foreach($servicehttps_array[$port] as $host) {

                    //skip if there is a custom config.
                    if (checkForCustomConfig($host,"HTTPS $port")) {
                    continue;
                    }

                    //Put additional check here.

                    //Service is good, add it to the list.
                    $service_list .= $host . ",";

                }

                $service_list=substr_replace($service_list,"",-1); //remove ending comma

                $service .="define service{\n";
                $service .="        use                             generic-service\n";
                $service .="        host_name                       $service_list\n";
                $service .="        service_description             HTTPS $port\n";
                $service .="        check_command                   check_web! --expect=$httpcodes -p $port -w 8 -c 9 --ssl\n";
                $service .="        check_interval                  5\n";
                $service .="        flap_detection_enabled          0\n";
                $service .="        retry_interval                  1\n";
                $service .="        notifications_enabled           0\n";
                $service .="        servicegroups                   https-checks-$port\n";
                $service .="        contact_groups                  OpsSysadmin\n";
                $service .="        notes                           HTTPS $port Website checks\n";
                $service .="}\n";
                array_push($servicegroups_array,"https-checks-$port");




            }
        }

        return($service);

    }

    function generateServiceHTTPSCert($servicehttps_array,$servicehttps_ports_array){

        $service_list = "";
        $service = "";
        global $servicegroups_array,$httpcodes;

        //loop over each port.
        foreach($servicehttps_ports_array as $port) {


            $service_list = "";

            if (count($servicehttps_array[$port]) > 0) {
                //loop over the array
                foreach($servicehttps_array[$port] as $host) {

                    //skip if there is a custom config.
                    if (checkForCustomConfig($host,"HTTPS $port SSL Cert Expiration")) {
                    continue;
                    }

                    //Put additional check here.

                    //Service is good, add it to the list.
                    $service_list .= $host . ",";

                }

                $service_list=substr_replace($service_list,"",-1); //remove ending comma

                $service .="define service{\n";
                $service .="        use                             generic-service\n";
                $service .="        host_name                       $service_list\n";
                $service .="        service_description             HTTPS $port SSL Cert Expiration\n";
                $service .="        check_command                   check_web!--expect=$httpcodes -p $port -w 8 -c 9 --ssl -C 20\n";
                $service .="        check_interval                  5\n";
                $service .="        flap_detection_enabled          0\n";
                $service .="        retry_interval                  1\n";
                $service .="        notifications_enabled           0\n";
                $service .="        servicegroups                   https-cert-checks-$port\n";
                $service .="        contact_groups                  OpsSysadmin\n";
                $service .="        notes                           HTTPS $port SSL Cert Expiration checks\n";
                $service .="}\n";
                array_push($servicegroups_array,"https-cert-checks-$port");



            }
        }

        return($service);

    }


    //------------------------------End of script. Functions below -------------------------

VB.NET

 <WebMethod()>
    Public Function Nagios_GenerateCustomServices(ByVal Hostname As String, ByVal MustBeSetToAutomatic As Boolean)
        Dim ReturnedArray As ArrayList
        If MustBeSetToAutomatic Then
            ReturnedArray = MyModule.DetectServerServices(Hostname, ServiceProcess.ServiceStartMode.Automatic)
        Else
            ReturnedArray = MyModule.DetectServerServices(Hostname, -1)
        End If

        Dim Host As String = "define host{
  use         linux-server
  host_name   " & Hostname & "
  alias       " & Hostname & "
  address     " & System.Net.Dns.GetHostByName(Hostname).AddressList(0).ToString & "
  notes       Ex. vBlock - VCE PowerPath
  hostgroups  Ex. vBlock_linux_appliance
    }
"

        Dim Data As String = Nothing

        Data = Host

        If MustBeSetToAutomatic Then

            For I = 0 To ReturnedArray.Count - 1

                If (ReturnedArray(I).ToString.StartsWith("!")) Then
                    Continue For
                End If

                Data &= "define service{
        use                             generic-service
        host_name                       " & Hostname & "
        service_description             " & ReturnedArray(I).ToString.Replace("\(", "(").Replace("\)", ")") & "
        check_command                   CheckServiceSNMP!" & ReturnedArray(I) & "
        check_interval                  60
        retry_interval                  1
        notification_interval           60
        contact_groups                  nicholas
        event_handler                   start_service!start_" & ReturnedArray(I) & "
        max_check_attempts              2
        notifications_enabled           1
}
" 'root@Hostname[Nagios]:/usr/lib64/nagios/plugins# ./check_SNMP_service_displayname_emc MySnmpCommunity IsPortal "Power"
            Next

        Else



            For I = 0 To ReturnedArray.Count - 1
                If Not (ReturnedArray(I).ToString.StartsWith("!")) Then
                    Continue For
                End If

                Data &= "define service{
        use                             generic-service
        host_name                       " & Hostname & "
        service_description             " & ReturnedArray(I).ToString.Substring(1).Replace("\(", "(").Replace("\)", ")") & "
        check_command                   CheckServiceSNMP!" & ReturnedArray(I) & "
        check_interval                  60
        retry_interval                  1
        notification_interval           60
        contact_groups                  TheGrouup
        event_handler                   start_service!start_" & ReturnedArray(I) & "
        max_check_attempts              2
        notifications_enabled           1
}
"
            Next
        End If

        Return Data

    End Function

Leave a Reply

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