Mikrotik. RouterOS 7. Автоматическое переключение между двумя провайдерами. Балансировка входящего трафика

Материал из Wiki
Версия от 21:13, 3 марта 2026; Cless (обсуждение | вклад) (Новая страница: «= Переключалка провайдеров + мониторинг провайдеров + входящие соединения input в микротик...»)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к навигации Перейти к поиску

Переключалка провайдеров + мониторинг провайдеров + входящие соединения input в микротик или проброс dst-nat с внешки до локального ip-адреса в локальную сеть через любого из 2-х провайдеров

Переключалка+балансировка

Ссылки

https://mikrotik-training.ru/files/MUoM/2021/kuznetsov.pdf

Настройка

Имеется 2 провайдера, у обоих есть статический внешний IP-адрес (Также инструкция подойдет для 3-х или более провайдеров с соответствующими дополнительными аналогичными настройками).

  • ether3-wan1_ttk_NEW - интерфейс ISP1
  • ether4-wan2_beeline_NEW - интерфейс ISP2
  • 213.129.118.1 - шлюз ISP1
  • 194.186.163.88 - шлюз ISP2
  • 77.88.8.8, 208.67.222.222 - внешние публичные 24/7 доступные IP

Необходимо:

  • ПРИ ОТКЛЮЧЕНИИ ОСНОВНОГО ПРОВАЙДЕРА ШЛЮЗ ПО-УМОЛЧАНИЮ ПЕРЕКЛЮЧАЕТСЯ НА РЕЗЕРВНОГО
  • чтобы сам микрот отвечал (например на ICMP запрос на внешний провайдерский IP-адрес) во внешку по тому провайдеру, по которому запрос пришел
  • чтобы при подключении с внешки до IP-адреса любого из 2-х провайдеров, мы могли подключиться до внутреннего сервера через проброс dst-nst


Создаем группу WAN интерфейсов

/interface list

add name=WAN

/interface list member

add interface=ether3-wan1_ttk_NEW list=WAN

add interface=ether4-wan2_beeline_NEW list=WAN


SRC-NAT на группе WAN интерфейсов

/ip firewall nat add action=masquerade chain=srcnat comment=NAT_masquerade_wan-all out-interface-list=WAN

ВАРИАНТ 1. 2 ISP

/routing table

add disabled=no fib name=route-table-gw1

add disabled=no fib name=route-table-gw2


/ip route

add comment=gw1 distance=201 gateway=213.129.118.1

add comment=gw2 distance=202 gateway=194.186.163.88

add comment=gw1_via_custom_route_table gateway=213.129.118.1 routing-table=route-table-gw1

add comment=gw2_via_custom_route_table gateway=194.186.163.88 routing-table=route-table-gw2

add comment=gw1_via_pub1_chk dst-address=77.88.8.8/32 gateway=213.129.118.1 scope=11

add comment=gw2_via_pub2_chk dst-address=208.67.222.222/32 gateway=194.186.163.88 scope=11

add check-gateway=ping comment=pub1_gw1_chk distance=101 gateway=77.88.8.8 target-scope=11

add check-gateway=ping comment=pub2_gw2_chk distance=102 gateway=208.67.222.222 target-scope=11


/ip firewall mangle

add action=mark-connection chain=prerouting connection-mark=no-mark in-interface=ether3-wan1_domru new-connection-mark=con-isp1 passthrough=yes

add action=mark-connection chain=prerouting connection-mark=no-mark in-interface=ether4-wan2_pppoe-client_intercon new-connection-mark=con-isp2 passthrough=yes

add action=mark-connection chain=prerouting connection-mark=no-mark in-interface=ether3-wan1_domru new-connection-mark=con-isp1 passthrough=yes

add action=mark-connection chain=prerouting connection-mark=no-mark in-interface=ether4-wan2_pppoe-client_intercon new-connection-mark=con-isp2 passthrough=yes

add action=mark-routing chain=prerouting connection-mark=con-isp1 in-interface-list=!WAN new-routing-mark=route-table-gw1 passthrough=yes

add action=mark-routing chain=prerouting connection-mark=con-isp2 in-interface-list=!WAN new-routing-mark=route-table-gw2 passthrough=yes

add action=mark-routing chain=output connection-mark=con-isp1 new-routing-mark=route-table-gw1 passthrough=yes

add action=mark-routing chain=output connection-mark=con-isp2 new-routing-mark=route-table-gw2 passthrough=yes

ВАРИАНТ 2. 3 ISP

/routing table

add disabled=no fib name=route-table-gw1

add disabled=no fib name=route-table-gw2

add disabled=no fib name=route-table-gw3


/ip route

add comment=gw1 distance=201 gateway=188.235.62.254

add comment=gw2 distance=202 gateway=ether4-wan2_pppoe-client_intercon

add comment=gw3 distance=203 gateway=172.24.199.1

add comment=gw1_via_custom_route_table gateway=188.235.62.254 routing-table=route-table-gw1

add comment=gw2_via_custom_route_table gateway=ether4-wan2_pppoe-client_intercon routing-table=route-table-gw2

add comment=gw3_via_custom_route_table gateway=172.24.199.1 routing-table=route-table-gw3

add comment=gw1_via_pub1_chk dst-address=77.88.8.8/32 gateway=188.235.62.254 scope=11

add comment=gw2_via_pub2_chk dst-address=208.67.222.222/32 gateway=ether4-wan2_pppoe-client_intercon scope=11

add comment=gw3_via_pub3_chk dst-address=77.88.8.3/32 gateway=172.24.199.1 scope=11

add check-gateway=ping comment=pub1_gw1_chk distance=101 gateway=77.88.8.8 target-scope=11

add check-gateway=ping comment=pub2_gw2_chk distance=102 gateway=208.67.222.222 target-scope=11

add check-gateway=ping comment=pub3_gw3_chk distance=103 gateway=77.88.8.3 target-scope=11


/ip firewall mangle

add action=mark-connection chain=prerouting connection-mark=no-mark in-interface=ether3-wan1_domru new-connection-mark=con-isp1 passthrough=yes

add action=mark-connection chain=prerouting connection-mark=no-mark in-interface=ether4-wan2_pppoe-client_intercon new-connection-mark=con-isp2 passthrough=yes

add action=mark-connection chain=prerouting connection-mark=no-mark in-interface=ether6-wan3_modem-4g new-connection-mark=con-isp3 passthrough=yes

add action=mark-connection chain=prerouting connection-mark=no-mark in-interface=ether3-wan1_domru new-connection-mark=con-isp1 passthrough=yes

add action=mark-connection chain=prerouting connection-mark=no-mark in-interface=ether4-wan2_pppoe-client_intercon new-connection-mark=con-isp2 passthrough=yes

add action=mark-connection chain=prerouting connection-mark=no-mark in-interface=ether6-wan3_modem-4g new-connection-mark=con-isp3 passthrough=yes

add action=mark-routing chain=prerouting connection-mark=con-isp1 in-interface-list=!-WAN- new-routing-mark=route-table-gw1 passthrough=yes

add action=mark-routing chain=prerouting connection-mark=con-isp2 in-interface-list=!-WAN- new-routing-mark=route-table-gw2 passthrough=yes

add action=mark-routing chain=prerouting connection-mark=con-isp3 in-interface-list=!-WAN- new-routing-mark=route-table-gw3 passthrough=yes

add action=mark-routing chain=output connection-mark=con-isp1 new-routing-mark=route-table-gw1 passthrough=yes

add action=mark-routing chain=output connection-mark=con-isp2 new-routing-mark=route-table-gw2 passthrough=yes

add action=mark-routing chain=output connection-mark=con-isp3 new-routing-mark=route-table-gw3 passthrough=yes


Готово

Пробуем пинговать с внешки IP-адреса провайдеров

Каждый должен пинговаться

Пробуем ходить с внешки на IP-адреса провайдеров по порту 80,

По каждому провайдеру проходим до веб-сервера 192.168.1.50

ОТКЛЮЧАЕМ ОСНОВНОГО ПРОВАЙДЕРА - ТРАФИК ИДЕТ ЧЕРЕЗ ШЛЮЗ РЕЗЕРВНОГО

Мониторинг провайдеров

Ссылки

https://vasilevkirill.ru/routeros-check-internet-v7/

Настройка

  • 213.129.118.208 - публичный адрес провайдера 1 на нашем микроте
  • 194.186.163.89 - публичный адрес провайдера 2 на нашем микроте
  • 213.129.118.1 - основной шлюз isp1
  • 194.186.163.88 - основной шлюз isp2

адреса, которые будем пинговать для проверки через isp1:

  • 176.99.13.13
  • 31.177.85.186

адреса, которые будем пинговать для проверки через isp2:

  • 93.158.134.1
  • 5.101.159.11


Создадим таблицы и правила для прохождения трафика до спец IP через определенных провайдеров


ПЕРВЫЙ ПРОВАЙДЕР:

/routing/table add name=via-isp1 fib comment="chk"

/routing/rule add dst-address=176.99.13.13/32 action=lookup-only-in-table table=via-isp1 comment="chk"

/routing/rule add dst-address=31.177.85.186/32 action=lookup-only-in-table table=via-isp1 comment="chk"

/ip route add dst-address=0.0.0.0/0 gateway=213.129.118.1 routing-table=via-isp1 comment="chk"


ВТОРОЙ ПРОВАЙДЕР:

/routing/table add name=via-isp2 fib comment="chk"

/routing/rule add dst-address=93.158.134.1/32 action=lookup-only-in-table table=via-isp2 comment="chk"

/routing/rule add dst-address=5.101.159.11/32 action=lookup-only-in-table table=via-isp2 comment="chk"

/ip route add dst-address=0.0.0.0/0 gateway=194.186.163.88 routing-table=via-isp2 comment="chk"

Создадим правила netwatch для проверки пингами спец внешних IP через определенных провайдеров


/tool netwatch

add comment=ns1.reg.ru disabled=no down-script="" host=176.99.13.13 http-codes="" interval=30s name=isp1-chk1 src-address=213.129.118.208 test-script="" thr-tcp-conn-time=1s type=icmp up-script=""

add comment=ns9.nic.ru disabled=no down-script="" host=31.177.85.186 http-codes="" interval=30s name=isp1-chk2 port=53 src-address=213.129.118.208 test-script="" thr-tcp-conn-time=1s type=icmp up-script=""

add comment=ns1.beget.com disabled=no down-script="" host=5.101.159.11 http-codes="" interval=30s name=isp2-chk2 port=53 src-address=194.186.163.89 test-script="" thr-tcp-conn-time=1s type=icmp up-script=""

add comment=ns2.yandex.ru disabled=no down-script="" host=93.158.134.1 http-codes="" interval=30s name=isp2-chk1 port=53 src-address=194.186.163.89 test-script="" thr-tcp-conn-time=1s type=icmp up-script=""


/tool netwatch

add comment=ns1.reg.ru disabled=no down-script="" host=176.99.13.13 http-codes="" interval=30s name=isp1-chk1 src-address=80.82.33.162 test-script="" thr-tcp-conn-time=1s type=icmp up-script=""

add comment=ns9.nic.ru disabled=no down-script="" host=31.177.85.186 http-codes="" interval=30s name=isp1-chk2 port=53 src-address=80.82.33.162 test-script="" thr-tcp-conn-time=1s type=icmp up-script=""

add comment=ns1.beget.com disabled=no down-script="" host=5.101.159.11 http-codes="" interval=30s name=isp2-chk2 port=53 src-address=178.210.43.248 test-script="" thr-tcp-conn-time=1s type=icmp up-script=""

add comment=ns2.yandex.ru disabled=no down-script="" host=93.158.134.1 http-codes="" interval=30s name=isp2-chk1 port=53 src-address=178.210.43.248 test-script="" thr-tcp-conn-time=1s type=icmp up-script=""


/system script add name=monitor


/system script edit monitor source

---

#####

#

# Monitor ros7 v.2026-02-14_isp2

# by Cless

#

#####

:local NetWatchIsp1CountUp [/tool/netwatch/print count-only where name~"isp1" disabled=no status=up];

:local NetWatchIsp2CountUp [/tool/netwatch/print count-only where name~"isp2" disabled=no status=up];

#ISP1 CHK

:if (($NetWatchIsp1CountUp > 0)) do={

    :global isp1Status "OK";

} else={

        :global isp1Status "FAIL";

    };

#ISP2 CHK

:if (($NetWatchIsp2CountUp > 0)) do={

    :global isp2Status "OK";

} else={

        :global isp2Status "FAIL";

    };

#ACTIVE GW CHK

:local gw1active [ip route get value-name=active [find where comment~"pub1_gw1_chk"]] ;

:local gw2active [ip route get value-name=active [find where comment~"pub2_gw2_chk"]] ;

:if (($gw1active=true) && ($gw2active!=true)) do={

    :global gwActive "gw1";

};

:if (($gw1active!=true) && ($gw2active=true)) do={

    :global gwActive "gw2";

};

# DEBUG

:global gwActive;

:global isp1Status;

:global isp2Status;

:put "gwActive $gwActive ; isp1Status $isp1Status ; isp2Status $isp2Status";

---


/system scheduler

add disabled=yes interval=30s name=chk on-event=chk policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon start-time=startup

add interval=1m name=monitor on-event=monitor policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon start-time=startup


Готово!


/system/script/environment/print

    ...

    2  gwActive        gw1

    3  isp1Status      OK

    4  isp2Status      OK

    ...

На Zabbix

apt install python3-librouteros


vim ./mikrotikVarGet.py


#!/usr/bin/python3

import sys

import json

from librouteros import connect

# ARGs check

if len(sys.argv) < 5:

    print("Usage: script.py <IP> <username> <password> <variable_name>")

    sys.exit(1)

# Connection parameters

IP = sys.argv[1]

USERNAME = sys.argv[2]

PASSWORD = sys.argv[3]

mikrotikApiVarName = sys.argv[4]

try:

    api = connect(

        host=IP,

        username=USERNAME,

        password=PASSWORD

    )

    all_vars = list(api('/system/script/environment/print'))

    for i, var in enumerate(all_vars):

        if var.get('name') == mikrotikApiVarName:

            print(var.get('value', ''))

            sys.exit(0)

except Exception as e:

    print(f"DEBUG: Error: {e}", file=sys.stderr)

    print("")

    sys.exit(1)


Далее на Zabbix проверяем значение переменных Item и создаем триггеры.


Например:

    mikrotikVarGet.py["{HOST.CONN}","uplit","Pass#","isp1Status"]