Страница 1 из 1

Отправка данных на WEB-сайт о недоступности сетевого ресурса

СообщениеДобавлено: 17 апреля 2020, 13:09
DmitryS


Пример использования программы IPAMon - ЗАПИСЬ LOG'а НА WEB-СТРАНИЦУ ПО ТРЕВОГЕ:

Задача: Отправлять строки, аналогичные строкам из LOG-файла, на страницу WEB-сайта при длительном отсутствии доступа к хосту (сетевому ресурсу, серверу, компьютеру и т.д.). Одновременно необходимо в режиме реального времени просматривать изменения, происходящие на странице, из любого интернет-браузера, с любого устройства, имеющего доступ к этой странице (сайту).

Описание: Для наглядности, в данном примере интервал отправки сообщений на электронную почту, в случае обнаружения недоступности хоста, равен 60 сек. Для более точного срабатывания "тревоги" необходимо подобрать оптимальные значения параметров: "количество ошибок для запуска файла" и "период запросов".



Устанавливаем на компьютер программу IPAMon и запускаем её:


Общие настройки программы:
Изображение


Вариант решения (через VBS и PHP скрипты):


Указываем какой файл запускать:
Изображение

Создаём файл "error.vbs" (в папке с программой) со следующим содержимым:
Option Explicit
On Error Resume Next
Dim WSHShell, objArgs, objWEB, objFile, txtFile
Dim isWD(8), isMY(13)
Dim iCnt, nCnt, nSec, nErr
Dim strIP, strTXT, strWait, strFile
Dim zRd, zRh, zRm, zRs
Dim sRd, sRh, sRm, sRs
iCnt = 0
nCnt = 0
nSec = 0
nErr = 0
zRd = 0
zRh = 0
zRm = 0
zRs = 0
sRd = "00000"
sRh = "00"
sRm = "00"
sRs = "00"
strIP = ""
strTXT = ""
strFile = ""
strWait = "00000-00:00:00"
isWD(0) = "Воскресенье"
isWD(1) = "Понедельник"
isWD(2) = "Вторник"
isWD(3) = "Среда"
isWD(4) = "Четверг"
isWD(5) = "Пятница"
isWD(6) = "Суббота"
isWD(7) = "Воскресенье"
isMY(0) = "Декабрь"
isMY(1) = "Январь"
isMY(2) = "Февраль"
isMY(3) = "Март"
isMY(4) = "Апрель"
isMY(5) = "Май"
isMY(6) = "Июнь"
isMY(7) = "Июль"
isMY(8) = "Август"
isMY(9) = "Сентябрь"
isMY(10) = "Октябрь"
isMY(11) = "Ноябрь"
isMY(12) = "Декабрь"
Set objFile = CreateObject("Scripting.FileSystemObject")
If objFile.FileExists("cfgs.res") Then
Set txtFile = objFile.OpenTextFile("cfgs.res", 1)
Do While txtFile.AtEndOfStream <> True
strFile = txtFile.ReadLine
If Len(Trim(CStr(strFile))) > 0 Then nCnt = nCnt + 1
If nCnt = 5 Then nSec = Abs(Int(Trim(CStr(strFile))))
If nCnt = 6 Then nErr = Abs(Int(Trim(CStr(strFile))))
Loop
txtFile.Close
Set txtFile = Nothing
End If
Set objFile = Nothing
If nErr < 2 Then nErr = 1
If nSec < 2 Then nSec = 1
If nErr > 86399 Then nErr = 86400
If nSec > 3599 Then nSec = 3600
nCnt = nSec * nErr
zRd = Abs(Int(nCnt / 86400))
zRh = Abs(Int((nCnt - zRd * 86400) / 3600))
zRm = Abs(Int((nCnt - zRd * 86400 - zRh * 3600) / 60))
zRs = Abs(Int((nCnt - zRd * 86400 - zRh * 3600 - zRm * 60)))
sRd = Trim(CStr(zRd))
sRh = Trim(CStr(zRh))
If Len(sRh) < 2 Then sRh = "0" + sRh
sRm = Trim(CStr(zRm))
If Len(sRm) < 2 Then sRm = "0" + sRm
sRs = Trim(CStr(zRs))
If Len(sRs) < 2 Then sRs = "0" + sRs
strWait = StrReverse(Left(StrReverse(sRd & "-" & sRh & ":" & sRm & ":" & sRs) + "00000", 14))
Err.Clear
Set objArgs = WScript.Arguments
If Err.Number = 0 Then
For iCnt = 0 to objArgs.Count - 1
If Len(Trim(objArgs(iCnt))) > 0 Then
strIP = Trim(objArgs(iCnt))
Exit For
End If
Next
strTXT = "[ " + Left(strIP + " ", 15) + _
" ] [ ОШИБКА ] [ " + strWait + " ] [ " + _
Trim(CStr(Date())) + " / " + Trim(CStr(Time())) + " / " + _
Trim(CStr(isWD(Weekday(Now, vbMonday))))+ " / " + _
Trim(CStr(isMY(Month(Now)))) + " ]"
Err.Clear
If Len(strIP) > 0 Then
Set WSHShell = WScript.CreateObject("WScript.Shell")
If Err.Number = 0 Then
Set objWEB = CreateObject("MSXML2.XMLHTTP.3.0")
If Err.Number = 0 Then
Randomize()
objWEB.Open "GET", _
"https://server.xx/write.php?log=00000000&txt=" & _
strTXT & "&rnd=" & Rnd(), False
objWEB.Send
End If
Set objWEB = Nothing
End If
End If
Set WSHShell = Nothing
End If
Set objArgs = Nothing
Err.Clear
WScript.Quit 0


Создаём файл "write.php" со следующим содержимым:
<?php
header('expires: Sat, 01 Jan 2000 00:00:00 GMT');
header('cache-control: no-cache, no-store, max-age=0, post-check=0, pre-check=0, must-revalidate', FALSE);
header('pragma: no-cache');
header("last-modified: ".gmdate("D, d M Y H:i:s ")."GMT");
?>
<?php
$log='';
$txt='';
if(isset($_GET['log']))
{
$log=$_GET['log'];
if($log=='00000000')
{
if(isset($_GET['txt']))
{
$txt=$_GET['txt'];
$txt=trim(strip_tags(trim($txt)));
if(strlen(strval($txt))>0)
{
if(file_exists("./".$log.".txt"))
{
$file=fopen("./".$log.".txt","a");
flock($file,2);
if($file)
{
fwrite($file," ".$txt." ".chr(13).chr(10));
}
}
}
flock($file,3);
fclose($file);
}
}
}
print(" ");
?>


Создаём файл "read.php" со следующим содержимым:
<?php
header('expires: Sat, 01 Jan 2000 00:00:00 GMT');
header('cache-control: no-cache, no-store, max-age=0, post-check=0, pre-check=0, must-revalidate', FALSE);
header('pragma: no-cache');
header("last-modified: ".gmdate("D, d M Y H:i:s ")."GMT");
$rnd="0.".substr(strval(rand()).strval(rand())."0000000000000000", 0, 16);
?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' http://www.w3.org/TR/xhtml1/DTD/xhtml1- ... l.dtd&#39;>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>IPAMon</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' />
<meta name='language' content='russian, english' />
<meta http-equiv='content-language' content='ru-ru' />
<meta http-equiv='content-script-type' content='text/javascript' />
<meta http-equiv='content-style-type' content='text/css' />
<meta http-equiv='content-type' content='text/html; charset=windows-1251' />
<meta http-equiv='expires' content='Sat, 01 Jan 2000 00:00:00 GMT' />
<meta http-equiv='cache-control' content='no-cache, no-store, max-age=0, post-check=0, pre-check=0, must-revalidate' />
<meta http-equiv='pragma' content='no-cache' />
<meta http-equiv='imagetoolbar' content='no' />
<meta http-equiv='refresh' content='60' />
<meta http-equiv='window-target' content='_top' />
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<style type='text/css'>
<!--
* {
top: 0px;
left: 0px;
margin: 0px;
padding: 0px;
border: 0px solid #ffffff;
color: #000000;
visibility: visible;
direction: ltr;
font-family: monospace;
font-size: 12px;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-decoration: none;
text-transform: none;
text-align: left;
line-height: 20px;
letter-spacing: normal;
word-spacing: normal;
white-space: normal;
text-indent: 0px;
text-decoration: none;
text-transform: none;
list-style: none;
outline: hidden;
outline-style: hidden;
outline-width: 0px;
table-layout: auto;
empty-cells: show;
caption-side: top;
float: none;
clear: none;
}
html {
width: 100%;
height: 101%;
overflow: auto;
overflow-x: hidden;
overflow-y: auto;
z-index: 0;
}
body {
overflow: hidden;
z-index: 1;
}
pre {
display: block;
white-space: pre;
z-index: 2;
}
-->
</style>
<script language='JavaScript' type='text/javascript'>
<!--
function isRedirect() {
<?php
print("top.location.href='https://server.xx/read.php?log=00000000&rnd=".$rnd."';\n");
?>
};
window.setInterval('isRedirect();', 60000);
//-->
</script>
</head>
<body>
<?php
$log='';
if(isset($_GET['log']))
{
$log=$_GET['log'];
if($log=='00000000')
{
if(file_exists("./".$log.".txt"))
{
print("<pre>\n");
include($log.".txt");
print("\n</pre>\n");
}
}
}
?>
</body>
</html>



Настройка:


01. Кладём файлы "write.php" и "read.php" на свой сайт, например:
      https://server.xx/write.php
      https://server.xx/read.php

02. Создаём пустой текстовый файл "00000000.txt" и кладём его туда же:
      https://server.xx/00000000.txt

03. В файле "read.php" можно задать частоту обновления страницы:
      а) <meta http-equiv='refresh' content='60' /> - в данном примере =60 сек.
      б) window.setInterval('isRedirect();', 60000); - тоже =60 сек.

04. В файлах "read.php" и "error.vbs" изменяем домен "server.xx" на свой!
    

Мониторинг:


Открываем в любом браузере ссылку https://server.xx/read.php?log=00000000 и смотрим записи:
Обновление страницы будет происходить автоматически каждые 60 сек., если это значение не было изменено (см. п. 3 выше).

Image




P.S.: В целях безопасности, можно изменить название LOG-файла "00000000" и его расширение ".txt" на другие. Файлы "read.php" и "write.php" можно также переименовать. Дополнительно можно все три файла положить во вложенную папку на сайте и ограничить доступ к LOG-файлу (00000000.txt), чтобы его невозможно было просмотреть напрямую.



Готовые файлы write.php, read.php, 00000000.txt и error.vbs можно взять ниже:

write.zip - write.php
read.zip - read.php
error.zip - error.vbs
00000000.zip - 00000000.txt