Display the status of servers from Zabbix to the desktop

    The Zabbix monitoring system provides excellent monitoring capabilities for servers running AIX, Linux, * BSD, Windows, Mac OS X, network equipment, Web applications, as well as any hardware that supports SNMP or at least ping. Zabbix is ​​free and licensed under the GPL. The server part of the system is installed only under * nix.
    You can configure sending notifications to email, jabber, sms when undesirable events occur, such as a server crash, excessive processor load, lack of disk space, etc. There is also a web interface with beautiful graphics and a network map.
    But the system administrator, as you know, is a lazy creature. Therefore, in order not to constantly climb into the web interface, it is advisable to display some graphics and a network map directly on its desktop.

    Handyman table

    In this article, we consider Windows XP / 7 as a client machine, but you can use the script on Linux with a little bit of finishing.



    How it works:
    Zabbix creates the necessary graphics and a network map that we want to display. The PHP script calls Zabbix once a minute, receives these images from it and generates one picture for the desktop from them. The figure is placed on the web server. Another script on the client machine periodically downloads this picture and sets it as wallpaper.

    Step 0. Install and configure Zabbix.
    This question has already been chewed up indocumentation , we will not dwell on it.
    The article uses version 1.8.2. In earlier versions, other image addresses are used, so if you have Zabbix 1.4 or 1.6, you will need to make adjustments to the script.

    Step 1. Create the necessary graphics and network maps in Zabbix.
    This step should also not cause difficulties.
    Graphs can be created on the Configuration - Hosts page , network map - in Maps .

    Step 2. We write a script that generates a desktop background image.
    We use PHP, the cURL extension for receiving images, the gd library and ImageMagick for working with images.
    First you need to create a user in Zabbix, under which the script will log into the system.
    The script will also receive the schedule for loading the WAN interface of the router from cacti and the image from the webcam in the server room. The graph in cacti seems more visual than the graph of Zabbix.
    The result of the script will be a BMP file.

    The script does not claim to be universal, but it is easy to remake it to fit your needs. Be sure to change the constant values ​​at the beginning of the file to the settings for your system. Step 3. Add the script in crowns It is advisable to store the script in a directory that is not published on the site. Otherwise, the script can be launched from the browser, and the cookie file can be dragged away. Add the script in crowns:


     

    //Основные настройки, не забудьте указать свои значения!

     

    //1. Папка для хранения изображений

    define('TMP_PATH', '/usr/local/share/zabbix/php/tmp/');

    //2. URL веб-интерфейса Zabbix

    define('ZABBIX_URL', 'http://monitoring.local/');

    //3. Пользователь в Zabbix

    define('ZABBIX_USER', 'mon');

    //4. Пароль для Zabbix

    define('ZABBIX_PW', 'qwerty');

    //5. Пользователь в Cacti

    define('CACTI_URL', 'http://monitoring.local/cacti/');

    //6. Пользователь в Cacti

    define('CACTI_USER', 'admin');

    //7. Пароль для Cacti

    define('CACTI_PW', 'qwerty');

    //8. Ширина рабочего стола в пикселях

    define('WALLPAPER_WIDTH', 1280);

    //9. Высота рабочего стола в пикселях

    define('WALLPAPER_HEIGHT', 1024);

    //10. Ресурсы, выводимые на рабочий стол и их координаты. 

    // Координаты придется считать вручную.

    $resources = array();

    //Карта сети

    $resources[] = array('url' => 'http://monitoring.local/map.php?noedit=1&sysmapid=2', 'x' => 280, 'y' => 0);

    //График температуры

    $resources[] = array('url' => 'http://monitoring.local/chart2.php?graphid=494&width=1138&period=86400', 'x' => 26, 'y' => 400);

    //Веб-камера

    $resources[] = array('url' => 'http://192.168.4.18/axis-cgi/jpg/image.cgi?resolution=320x240', 'x' => 960, 'y' => 690);

    //График из cacti

    $resources[] = array('url' => 'http://monitoring.local/cacti/graph_image.php?local_graph_id=5&rra_id=0&view_type=tree&graph_start=' . (time() - 86400) . '&graph_end=' . time(), 'x' => 357, 'y' => 690);

     

    //Конец настроек

    //Ниже менять ничего не надо, если вы не уверены, что вы делаете.

     

    $error = false;

     

    //"Логинимся" скриптом в Zabbix

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, ZABBIX_URL . '/index.php');

    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_POSTFIELDS, array('form'=>'1', 'form_refresh'=>'1','name'=>ZABBIX_USER, 'password'=>ZABBIX_PW,'enter'=>'Enter'));

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    curl_setopt($ch, CURLOPT_COOKIEJAR, "./cookie.txt"); //Сохраняем куки в файл

    curl_setopt($ch, CURLOPT_COOKIEFILE, "./cookie.txt");

     

    $t = curl_exec($ch);

    curl_close($ch);

     

     

    //"Логинимся" скриптом в cacti. Удалите эти строчки, если вы не используете cacti

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, CACTI_URL . '/graph_image.php');

    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_POSTFIELDS, array('action'=>'login', 'login_username'=>CACTI_USER,'login_password'=>CACTI_PW));

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    curl_setopt($ch, CURLOPT_COOKIEJAR, "./cookie.txt");

    curl_setopt($ch, CURLOPT_COOKIEFILE, "./cookie.txt");

     

    $t = curl_exec($ch);

    curl_close($ch);

     

    //Получаем изображения

    foreach($resources as $k => $res)

    {

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $res['url']);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_COOKIEJAR, "./cookie.txt");

    curl_setopt($ch, CURLOPT_COOKIEFILE, "./cookie.txt");

     

    $file = curl_exec($ch);

    if($file) file_put_contents(TMP_PATH . 'temp_img' . $k . '.tmp', $file);

    else $error = true;

    curl_close($ch);

    }

     

    //Создаем "обои" на рабочий стол

    $wp = imagecreatetruecolor(WALLPAPER_WIDTH, WALLPAPER_HEIGHT);

     

    if(!$error)

    {

    //Все в порядке

     

    //Заливаем синим фоном

    $bg = imagecolorallocate($wp, 58, 110, 165);

    imagefill($wp, 0, 0, $bg);

     

    //Добавляем картинки

    $images = array();

    foreach($resources as $k => $res)

    {

    $im = imagecreatefromfile(TMP_PATH . 'temp_img' . $k . '.tmp');

    if(!$im)

    {

    $error = true;

    break;

    }

    imagecopy($wp, $im, $res['x'], $res['y'], 0, 0, imagesx($im), imagesy($im));

    imagedestroy($im);

    }

    imagepng($wp, TMP_PATH . 'temp_fin.png');

    }

     

    if($error)

    {

    //Если произошла ошибка, заливаем рабочий стол серым цветом

    $bg = imagecolorallocate($wp, 192, 192, 192);

    imagefill($wp, 0, 0, $bg);

    }

     

    //Конфертируем полученный PNG файл в BMP с помощью ImageMagick

    $imgk = new Imagick(TMP_PATH . 'temp_fin.png');

    $imgk->pingImage(TMP_PATH . 'temp_fin.png');

    $imgk->readImage(TMP_PATH . 'temp_fin.png');

    $imgk->setImageCompression(imagick::COMPRESSION_NO);

    $imgk->setImageFormat("bmp");

    $imgk->writeImage(TMP_PATH . 'wp.bmp');

     

     

    //Функция открытия изображения в зависимости от его типа с сайта php.net

    function imagecreatefromfile($path)

    {

        $info = @getimagesize($path);   

        if(!$info) return false;

     

        $functions = array(

            IMAGETYPE_GIF => 'imagecreatefromgif',

            IMAGETYPE_JPEG => 'imagecreatefromjpeg',

            IMAGETYPE_PNG => 'imagecreatefrompng',

            IMAGETYPE_WBMP => 'imagecreatefromwbmp',

            IMAGETYPE_XBM => 'imagecreatefromwxbm',

            );

     

        if(!$functions[$info[2]]) return false;

     

        if(!function_exists($functions[$info[2]])) return false;

     

        return $functions[$info[2]]($path);

    }

    ?>





    # echo "*/1 * * * * root /usr/local/bin/php /usr/local/share/zabbix/get_image.php > /dev/null 2>&1" >> /etc/crontab
    Zabbix, by default, updates data every 30 seconds, so you can update the picture once a minute.

    Step 4. Install the script for automatic wallpaper change on the client machine.
    Let's create a VBS script:
    For Windows XP Windows Vista / Windows 7 Here the situation is more complicated. To change the wallpaper, you need to call the WinAPI function. VBScript cannot do this, so we will have to write a small program in C ++. The idea is taken from here . At the end of the article there is a reference to the compiled exe-Schnick, but just in case quote the source code: You now need to VBS script for Windows XP to replace the string at Step 5. Add the VBS script in task scheduler
    Dim res

    Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP") 

    oXMLHTTP.Open "GET", "http://monitoring.local/tmp/wp.bmp", 0'адрес сайта 

    oXMLHTTP.Send

    On Error Goto 0 

     

    Set oADOStream = CreateObject("ADODB.Stream") 

    oADOStream.Mode = 3 

    oADOStream.Type = 1 

    oADOStream.Open 

    oADOStream.Write oXMLHTTP.responseBody 

    oADOStream.SaveToFile "C:\\wp.bmp", 2'куда файл сохранять

    Set oXMLHTTP = Nothing

    Set oADOStream = Nothing

     

     

    Dim WshShell

    Set WshShell = WScript.CreateObject("Wscript.Shell")

    WshShell.RegWrite "HKCU\Control Panel\Desktop\Wallpaper", """C:\\wp.bmp"""

    WshShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters", 1, True

     

    Set WshShell = Nothing






    #include 

    #include 

    #include 

    int main(int argc, char **argv)

    {

    if(argc == 0) return 1;

    SystemParametersInfo( SPI_SETDESKWALLPAPER, 0, (PVOID)argv[1], SPIF_UPDATEINIFILE | SPIF_SENDCHANGE );

    return 0;

    }

     


    WshShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters", 1, True

    WshShell.Run "C:\wallpaper.exe C:\wp.bmp", 1, True


    You must run the script once a minute.

    Done!

    Project files - zabbix_wallpaper.zip .

    Also popular now: