- Netwatch
- Properties
- Type-specific options
- ICMP probe options
- TCP-CONNECT/HTTP-GET probe options
- TCP-CONNECT pass-fail criteria
- HTTP-GET probe pass/fail criteria
- Probe statistics/variables
- Generic:
- Status
- Quick Example
- Knowledge WiKibase
- Инструменты пользователя
- Инструменты сайта
- Содержание
- Оповещение о восстановлении Интернет-соединения на MikroTik
- Логика работы
- Важное замечание
- Комментарии к коду
- netwatch
- internet-down
- internet-up
- Код для импорта
- Политики запуска
- Manual:Tools/Netwatch
- Contents
- Summary
- Properties
- Status
- Basic examples
Netwatch
Netwatch monitors the state of hosts on the network. Monitoring can be done with the following probe types:
1) ICMP — pings to a specified IP address — hosts, with an option to adjust threshold values
2) Simple — uses ping, without use of advanced metrics
3) TCP conn, to test the TCP connection
4) HTTP GET, request against a server you are monitoring
For each entry in the Netwatch table, you can specify an IP address, ping interval, and console scripts. The main advantage of Netwatch is its ability to issue arbitrary console commands on host state changes.
Properties
Sub-menu: /tool/netwatch
Property | Description | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
host (Default:»») | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
type (icmp| tcp-conn|http-get|simple; Default: simple) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
interval (Default: 10s) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
timeout (Default: 3s) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
start-delay (Default: 3s) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
up-script (Default:»») | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
down-script (Default:»») | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
test-script (Default:»») |
Property | Description |
---|---|
packet-interval (Default: 50ms) | The time between ICMP-request packet send |
packet-count (Default: 10) | Total count of ICMP packets to send out within a single test |
packet-size (Default: 54 (IPv4) or 54 (IPv6)) | The total size of the IP ICMP packet |
thr-rtt-max (Default: 1s) | Fail threshold for rtt-max (a value above thr-max is a probe fail) |
thr-rtt-avg (Default: 100ms) | Fail threshold for rtt-avg |
thr-rtt-stdev (Default: 250ms) | Fail threshold for rtt-stdev |
thr-rtt-jitter (Default: 1s) | Fail threshold for rtt-jitter |
thr-loss-percent (Default: 85.0%) | Fail threshold for loss-percent |
thr-loss-count (Default: 4294967295(max)) | Fail threshold for loss-count |
TCP-CONNECT/HTTP-GET probe options
Property | Description |
---|---|
port (Default: 80) | TCP port (for both tcp-conn and http-get probes) |
TCP-CONNECT pass-fail criteria
Property | Description |
---|---|
thr-tcp-conn-time (Default: 1s) | Fail threshold for tcp-connect-time |
HTTP-GET probe pass/fail criteria
Property | Description |
---|---|
thr-http-time (Default: 10s) | Fail threshold for http-resp-time |
http-code-min (Default: 100) | OK/fail criteria for HTTP response code. |
http-code-max (Default: 299) | Response in the range [ http-code-min , http-code-max ] is a probe pass/OK; outside — a probe fail. See mozilla-http-status or rfc7231 |
Probe statistics/variables
You can view statistics and use these variables in scripting, keep in mind that variables containing «-» must be written like this, for example, «done-tests» would be $»done-tests»
Generic:
Property | Description | |||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
name | user added name for Netwatch entry | |||||||||||||||||||||||||||||||||||||||||||||
comment | ||||||||||||||||||||||||||||||||||||||||||||||
done-tests | total count of probe tests already done so far | |||||||||||||||||||||||||||||||||||||||||||||
failed-tests |
Property | Description |
---|---|
sent-count | ICMP packets sent out |
response-count | Matching/valid ICMP packet responses received |
loss-count | number of lost packets |
loss-percent | number of lost packets in percent |
rtt-avg | mean value of rtt (packet roundtrip time) |
rtt-min | min rtt |
rtt-max | max rtt |
rtt-jitter | jitter ( = max — min) of rtt |
rtt-stdev | standard deviation of rtt |
Property | Description |
---|---|
tcp-connect-time | time taken to establish a TCP connection |
Property | Description |
---|---|
http-status-code | HTTP response status code (200 OK, 404 Not Found, etc.). See mozilla-http-status or RFC7231 |
On each probe’s OK/fail state change:
- probe identification info and OK->fail or fail->OK is printed to info level
- detailed probe stats and config is printed to debug level
Status
Command /tool/netwatch/print will show the current status of Netwatch and read-only properties:
- since — Indicates when a state of the host changed last time;
- status — Shows the current status of the host;
- host — address being monitored
Quick Example
Here we will use a simple ICMP check to host with IP 8.8.8.8:
Afterward, in the logging section we can see Netwatch executed script:
Knowledge WiKibase
…collecting bit by bit!
Инструменты пользователя
Инструменты сайта
Содержание
Оповещение о восстановлении Интернет-соединения на MikroTik
Прошел тут у нас недавно во Владивостоке ледяной дождь. Небывалых масштабов и разрушений! И, конечно же, пропал Интернет! Вовсе! Надолго!
Первый день я иногда подключался к роутеру и смотрел, а не появился ли он, искомый. Во второй день уже что-то поднадоело! А на третий день появились эти скрипты. В итоге, через 5 дней мне на почту свалилось уведомление, что Интернет есть и можно расслабиться.
В отличии от полноценного фэйловера, в данном случае я решил использовать утилиту Netwatch из пакета Advanced Tools – во-первых, для разнообразия, а, во-вторых, чтобы не нагружать периодическим выполнением скриптов и так не очень мощный маршрутизатор hAP .
Логика работы
Утилита Netwatch периодически проверяет связь с указанным хостом и, если она пропадает, один раз выполняет инструкции из раздела Down , а когда появляется – один раз из раздела Up .
Эти разделы ссылаются на соответствующие скрипты, которые:
При реализации этого же, но только через скрипты, пришлось бы еще писать счетчик, который подавлял бы выдачу постоянных уведомлений, а так, это не нужно.
Важное замечание
В принципе, в разделах Up и Donw можно расположить сами скрипты, но! У Netwatch есть две проблемы 1) :
Поэтому приходится размещать тексты скриптов отдельно и во всех обязательно включать Don’t Require Permissions !
Комментарии к коду
Вся эта затея сводится к настройке Netwatch и добавлению двух 2) скриптов.
netwatch
Тут все просто – что пингуем 3) , с какой периодичностью и названия наших скриптов. Таймаут по умолчанию 1000 мс, но я поставил 300 и это нормально работает.
internet-down
Вводим переменные для работы преобразователя даты в нормальную.
Текст, выводящийся в логах, когда Интернет падает.
Получаем и преобразовываем дату в нормальный вид. Получаем время.
Пишем в файл дату и время. Если файла нет, создаем его и опять таки пишем в него дату и время. Задержка нужна обязательно, т.к. иначе файл не успевает создаться и… все плохо.
Пишем в лог ошибку о том, что нет Интернета.
internet-up
Электронный адрес того, кого будем оповещать.
Объявляем необходимые переменные.
Поучаем и преобразовываем дату. Получаем время.
Получаем в переменную internetStatus значение из файла, если его нет, создаем его и устанавливаем в значение none , т.е. нет даты и времени предыдущего отключения Интернета – это нужно, т.к. при запуске или перезагрузке устройства Netwatch сразу же проверяет соединение с хостом. По сути, это бонус, позволяющий отслеживать незапланированные перезагрузки роутера.
Вводим всякие разные тексты.
Отправляем письмо, если ошибка, пишем в лог.
Сбрасываем значение в файле.
Код для импорта
Разработано для RouterOS v6.45.1, проверено на v6.47.8.
Политики запуска
Это минимально необходимый набор для работы скрипта.
Manual:Tools/Netwatch
Contents
Summary
Netwatch monitors state of hosts on the network. It does so by sending ICMP pings to the list of specified IP addresses. For each entry in netwatch table you can specify IP address, ping interval and console scripts. The main advantage of netwatch is it’s ability to issue arbitrary console commands on host state changes.
Warning: Netwatch executes scripts as *sys user, so any defined global variable in netwatch script will not be readable by scheduler or other users
Properties
Sub-menu: /tool netwatch
Property | Description |
---|---|
down-script (string; Default: ) | Console script that is executed once when state of a host changes to down |
host (IP; Default: 0.0.0.0) | IP address of the host that should be monitored |
interval (time; Default: 1m) | Time interval between pings. Lowering this will make state changes more responsive, but can create unnecessary traffic and consume system resources. |
timeout (time; Default: 1s) | Timeout in seconds after which host is considered down |
up-script (string; Default: ) | Console script that is executed once when state of a host changes to up |
Warning: Since RouterOS v6.42 Netwatch is limited to read,write,test,reboot script policies. If the owner of the script does not have enough permissions to execute a certain command in the script, then the script will not be executed. If the script has greater policies than read,write,test,reboot , then the script will not be executed as well, make sure your scripts do not exceed the mentioned policies.
Note: It is possible to disable permission checking for RouterOS scripts under /system scripts menu. This is useful when Netwatch does not have enough permissions to execute a script, though this decreases overall security. It is recommended to assign proper permissions to a script instead.
Status
Command /tool netwatch print will show current status of netwatch and read-only properties listed in table below:
Property | Description |
---|---|
since (time) | Indicates when state of the host changed last time |
status (up | down | unknown) | Shows the current status of the host |
Basic examples
This example will run the scripts gw_1 or gw_2 which change the default gateway depending on the status of one of the gateways:
Without scripts, netwatch can be used just as an information tool to see which links are up, or which specific hosts are running at the moment.
Let’s look at the example above — it changes default route if gateway becomes unreachable. How it’s done? There are two scripts. The script «gw_2» is executed once when status of host changes to up. In our case, it’s equivalent to entering this console command:
The find command returns list of all routes whose dst-address value is 0.0.0.0/0. Usually, that is the default route. It is substituted as first argument to /ip route set command, which changes gateway of this route to 10.0.0.217
The script «gw_1» is executed once when status of host becomes down. It does the following:
It changes the default gateway if 10.0.0.217 address has become unreachable.
Here is another example, that sends e-mail notification whenever the 10.0.0.215 host goes down: