Mikrotik отключить порт ethernet
Базовая настройка защиты роутера MikroTik: настройка устройства, настройка сетевого экрана, защита от сканирования портов, защита от подбора пароля.
🔔 В статье даны примеры команд в терминале MikroTik. Если при вставке команды в терминал, происходит автоматическая вставка команд (при выполнении вы получаете ошибку bad command name или expected end of command), нажмите сочетание Ctrl+V, чтобы отключить эту возможность.
Monitor
To print out a current link rate, duplex mode, and other Ethernet related properties or to see detailed diagnostics information for transceivers, use /interface ethernet monitor command. The provided information can differ for different interface types (e.g. Ethernet over twisted pair or SFP interface) or for different transceivers (e.g. SFP and QSFP).
- disabled - negotiation disabled
- done - negotiation completed
- failed - negotiation failed
- incomplete - negotiation not completed yet
- short - support short cables
- standard - support standard cables
- link-ok - the card is connected to the network
- no-link - the card is not connected to the network
- unknown - the connection is not recognized (if the card does not report connection status)
Example output of an Ethernet status:
Example output of a SFP status:
Stats
Using /interface ethernet print stats command, it is possible to see a wide range of Ethernet related statistics. The list of statistics can differ between RouterBoard devices due to different Ethernet drivers. The list below contains all available counters across all RouterBoard devices. Most of the Ethernet statistics can be remotely monitored using SNMP and MIKROTIK-MIB.
For example, output of Ethernet stats on hAP ac2 device:
Блокировка сканеров портов
Правило превентивной блокировки — блокируем ботов/пользователей сканирующих порты устройств в интернете, для поиска уязвимостей. Составим список не используемых портов нашим роутером, внесем в BlackList IP адреса устройств, кто пытается обратиться к указанным портам.
Для защиты от сканеров, которые целенаправленно ищут устройства MikroTik — добавим в список неиспользуемые порты (сервисы MikroTik) и стандартный порт Winbox 8291 (который мы сменили по рекомендации). Добавим популярные уязвимые порты роутеров (если злоумышленник проверяет на роутере данные порты, полностью заблокируем ему доступ).
Применять правило будем только для новых соединений.
TCP порты ловушки
Создать правило
Помещаем IP адрес недоверенного устройства в BlackList, на 10 часов:
Разместите правило, ориентируясь на его номер в комментарии.
🚯 За 10 часов в BlackList находится около 500 IP адресов выполняющих попытки сканировать «уязвимые порты» роутера MikroTik.
NAT: как разрешить (запретить) интернет по расписанию
Вы можете запрещать или разрешать доступ к интернету по времени, используя настройку правила masquerade (NAT).
Отредактируйте правило masquerade, на вкладке Extra:
Сбрасываем неразрешенные соединения
Правило «Drop all» — отбросим все соединения, которые не были разрешены раньше и не входят в список доверенных (внутренних) интерфейсов (InternalInterfaces).
Поместите правило на последнюю позицию в правилах Firewall Filter Rules.
Create script
Specify the following variables in the script:
- InterfaceName – interface name (in the example wlan2-5GHz);
- StartEnableTime – time, from which the interface should be turned on (in the example 08:00:00);
- EndEnableTime – time, after which the interface should be turned off (in the example 20:00:00).
Список «Внутренние интерфейсы»
Помещаем в этот список интерфейсы локальной сети, VPN подключения и т.д.
Содержание
Firewall правило: как отключить (включить) интерфейс по расписанию
Чтобы отключить или включить интерфейсы по расписанию, можно использовать настройку правила межсетевого экрана (Firewall) на вкладке Extra.
⚠️ Для работы правила, интерфейс должен являться master интерфейсом.
Например: ограничим работу WiFi интерфейса (wlan2-5GHz) в нерабочее время, с 19:00 до 07:00.
Если вы желаете запретить работу интерфейса в субботу и воскресенье (полный день), установите значения времени:
Switch
Sub-menu: /interface ethernet switch
This submenu allows configuration of certain RouterBoard switch chip features. Read more >>.
Черный список
Создать список
Создаем список BlackList, в который будем помещать IP адреса, которым по какой-то причине запрещен доступ к MikroTik или защищаемым устройствам.
Создать правило
Создадим правило «BlackList» отклоняющее запросы от IP адресов из списка BlackList.
Для экономии ресурсов центрального процессора, запрещающее правило разместим в таблице Prerouting.
⚠️ Правила размещенные в Prerouting выполняются до разделения трафика на цепочки Input и Forward!
Поместите правило по его номеру в комментарии.
На скриншоте видно дополнительные правила:
Интерфейсы
Объединим внутренние (доверенные) и внешние (недоверенные) интерфейсы в списки, для удобства дальнейшего управления.
Комментарии 18
Здравствуйте. Воспользовался вашей статьей для защиты от Bruteforce.
Непонятно следующее в разделе «Блокируем Bruteforce»:
Где указывается повторная попытка? Мой роутер сразу заносит в черных список после первого ввода неверного пароля.
Так же мой роутер заносит в черный список только если стучатся через winbox. Попытки подбора пароля через браузер продолжают проходить. Где посмотреть корректность настройки?
Большое спасибо Евгений! Поправил.
Как оградиться от влазивающей соседки. Доступ к роутеру и ноуту есть. Не таскать же их с собой. Пароли менять боится — докажу что не сосед лезет. Вот только восстановил сеть. Начались выбрасывания из сети
И кстати, её IP я не вижу. Даже в настройках роутера
Едрён-батон, хоть бы слово понял. Это что? Куда прописывать? Ребята, вы ж для чайников пишете. Третья сотня водки зазря ушла. Эхххх. Не быть мне под защитой.
Что именно непонятно? Попробую помочь.
В квадратных скобках указана последовательность нажатия кнопок в окне Winbox.
Просто фраза, типа, «введите». Не понимаю куда вводить. Не в досе же в конце концов прописывать). Где то в настройках роутера. А там их тьма тьмущая. И все не русские. А в языке ангелов я, извините, профан.
У каждого пункта статьи указано два варианта выполнения:
1. вариант нажимать на пункты меню Winbox, они подписаны в квадратных скобках;
2. вариант «вводить» в терминал MikroTik (в окне управления Winbox, нажмите на кнопку New Terminal).
Например в первом пункте Пользователи:
Нажмите на кнопку [System], потом на кнопку [Users], в открывшемся окне нажмите на вкладку [Groups], потом на кнопку [+] и введите параметры нового пользователя.
Но, если нет знаний по оборудованию MikroTik, я бы не рекомендовал самостоятельную настройку этого оборудования или использовать вариант QuckSet (Быстрая настройка) из меню Winbox (этот «матер настройки» в меру удобно и безопасно настроит устройство).
Хотя если есть время и любопытство, то можно встать на тернистый путь настройки устройства с 0. 🙂 Но в комментариях это будет делать не так просто. 🙂
вот КМК полезные правила в RAW
/ip firewall raw
add action=drop chain=prerouting comment=»drop blocked list» dst-address-list=blocked_list
add action=drop chain=prerouting comment=»drop bruteforces» src-address-list=bruteforce_blacklist
add action=drop chain=prerouting comment=»drop from guest to local» dst-address-list=local_network src-address-list=guest_network
add action=drop chain=prerouting comment=»drop DNS» dst-port=53 in-interface-list=list_all_wan protocol=tcp
add action=drop chain=prerouting comment=»drop DNS» dst-port=53 in-interface-list=list_all_wan protocol=udp
add action=drop chain=prerouting comment=»drop SNPP» dst-port=444 in-interface-list=list_all_wan protocol=tcp
add action=drop chain=prerouting comment=»drop SNPP» dst-port=444 in-interface-list=list_all_wan protocol=udp
add action=drop chain=prerouting comment=»drop SMB» dst-port=445 in-interface-list=list_all_wan protocol=tcp
add action=drop chain=prerouting comment=»drop SMB» dst-port=445 in-interface-list=list_all_wan protocol=udp
add action=drop chain=prerouting comment=»drop NetBIOS» dst-port=137,138,139 in-interface-list=list_all_wan protocol=udp
1. Каждое правило которое будет добавлено в Firewall, является «преградой» для трафика, который проходит через ваш роутер. Обработка каждого правила затрачивает ресурсы CPU вашего роутера.
При больших объемах трафика, при большом количестве правил, при большом объеме выполняемых скриптов и слабом CPU роутера — это может оказаться проблемой, которая проявляется неожиданно.
Поэтому я стараюсь писать минимум правил и использовать объединение правил.
2. По мне это большой избыток правил, которые заставят CPU вашего роутера заниматься пустой тратой ресурсов. Посмотрите счетчик правила и оцените, какое количество пакетов, от общего числа блокируется данным правилом и оцените полезную нагрузку (каждое из правил это преграда для всех пакетов обрабатываемых роутером). В статье, все это будет отбрасываться последним правилом.
Так же рекомендую учесть «расположение роутера», большинство пользователей находится за NAT провайдера с «серым IP адресом», у них в целом отсутствует возможность прямого обращения извне и подобные правила будут создавать совершенно бесполезную нагрузку.
Например тестовый роутер с «белым IP адресом» заблокировал 8000 попыток обращения к уязвимым портам, а роутер за NAT провайдера — 270 попыток, за 6 дней.
Если количество обращений по данным портам — значительно, стоит выделить блокировку в отдельное правило, для снижения нагрузки на CPU роутера.
Если кто-то «хитрый» каким либо способом узнает вашу подсеть и пропишет у себя маршрут до вашей сети, то будучи в сети провайдера, попадет к вам в сеть. Хорошо бы запретить весь входящий трафик на wan не dst-nat
add action=drop chain=forward comment=»drop forward new in \»list_all_wan\» !dstnat» connection-nat-state=!dstnat connection-state=new in-interface-list=list_all_wan
Задача статьи не стоит «Всеобъемлющее руководство по максимальной защите MikroTik на все случаи жизни».
Сомнительной полезности правило в случае, если в локалку проброшены какие-то порты
Правило конечно крутое
, но как быть с DNS ?
Я настраиваю Firewall по правилу «запрещено всё, что не разрешено» (и советую делать так же), хотя есть вариант настройки Firewall «разрешено всё, что не запрещено».
В моём случае трафик на 53 порт, с внешних интерфейсов будет отброшен финальным правилом, так же как и любой другой не разрешенный предыдущими правилами.
Я часто нахожу совет отклонения запросов на 53 порт (как и многих других) отдельным правилом, но перед написанием статьи у меня больше недели велись логи обращения к портам устройства.
Сравнив количество обращений к портам, были выбраны именно указанные в статье порты.
Я не отрицаю, что в практике сетевого администратора может быть и другой опыт, когда поток запросов на этот порт превысит совокупное обращение к другим портам, в этом случае, для снижения нагрузки на роутер, можно вынести отдельное правило в таблицу Prerouting (RAW).
Если я правильно понимаю, то вы запрещаете «TCP порты ловушки», но там отсутствует порт 53 (а там еще UDP).
На сколько я знаю, для микротика по нагрузке одинаково, сделаете вы 10 одинаковых правил с разными портами или сделаете одно правило с 10 портами через запятую.
MikroTik RouterOS supports various types of Ethernet interfaces - ranging from 10Mbps to 10Gbps Ethernet over copper twisted pair, 1Gbps and 10Gbps SFP/SFP+ interfaces and 40Gbps QSFP interface. Certain RouterBoard devices are equipped with a combo interface that simultaneously contains two interface types (e.g. 1Gbps Ethernet over twisted pair and SFP interface) allowing to select the most suitable option or creating a physical link failover. Through RouterOS, it is possible to control different Ethernet related properties like link speed, auto-negotiation, duplex mode, etc, monitor a transceiver diagnostic information and see a wide range of Ethernet related statistics.
Межсетевой экран
Настраиваем ограничения доступа к роутеру и устройствам сети с помощью межсетевого экрана MikroTik.
⚠️ Перед добавлением ограничивающих правил — включите Безопасный режим MikroTik!
Add script to Scheduler
To run the script, you need permission: read, write, test, policy.
🟢 How to disable (enable) the MikroTik interface on a schedule or allow (deny) access to the Internet by time was discussed in this article. I hope you have chosen a suitable way to manage the state of the interface. However, if you run into any problems while setting up, feel free to write in the comments. I will try to help.
The script is checked: hAP ac lite [RouterBOARD 952Ui-5ac2nD], RouterOS 6.48.1 (stable).
Пользователи
Создайте нового пользователя с уникальным именем и удалите встроенную учетную запись системного пользователя по умолчанию — admin.
Не используйте простые имена пользователя, пароль должен соответствовать требованиям безопасности.
Если доступ к устройству имеют несколько пользователей, вы можете более подробно задать права выбранному пользователю. Создайте новую группу и определите права пользователей этой группы.
Соседи
Настроим обнаружение устройства используя Neighbor Discovery только для внутренних интерфейсов или разрешенных интерфейсов.
Разрешаем обнаружение только с интерфейсов перечисленных в списке InternalInterfaces.
Разрешить установленные и связанные соединения
Правило «Trusted» — разрешаем уже установленные и связанные подключения, для снижения нагрузки на центральный процессор роутера.
Помещаем правило первым в списке Filter Rules (поместите правило ориентируясь на его номер в комментарии).
Firewall rule: how to disable (enable) an interface on a schedule
To disable or disable the interface on a schedule, you can use the Firewall rule setting on the Extra tab.
⚠️ For the rule to work, the interface must be the main interface.
For example: we will restrict the operation of the WiFi interface (wlan2-5GHz) during non-working hours, from 19:00 to 07:00.
If you want to disable the operation of the interface on Saturday and Sunday (full day), set the time values:
Detect Cable Problems
Cable test can detect problems or measure the approximate cable length if the cable is unplugged on the other end and there is therefore, "no-link". RouterOS will show:
- which cable pair is damaged
- the distance to the problem
- how exactly the cable is broken - short-circuited or open-circuited
This also works if the other end is simply unplugged - in that case, the total cable length will be shown.
Here is example output:
In the above example, the cable is not shorted but “open” at 4 meters distance, all cable pairs equally faulty at the same distance from the switch chip.
Currently cable-test is implemented on the following devices:
- CCR series devices
- CRS1xx series devices
- CRS2xx series devices
- OmniTIK series devices
- RB450G series devices
- RB951 series devices
- RB2011 series devices
- RB4011 series devices
- RB750Gr2
- RB750UPr2
- RB751U-2HnD
- RB850Gx2
- RB931-2nD
- RB941-2nD
- RB952Ui-5ac2nD
- RB962UiGS-5HacT2HnT
- RB1100AHx2
- RB1100x4
- RBD52G-5HacD2HnD
- RBcAPGi-5acD2nD
- RBmAP2n
- RBmAP2nD
- RBwsAP-5Hac2nD
- RB3011UiAS-RM
- RBMetal 2SHPn
- RBDynaDishG-5HacD
- RBLDFG-5acD
- RBLHGG-5acD
Note: Currently cable-test is not supported on Combo ports.
Разрешим порт Winbox
Правило «Winbox» — разрешаем подключение на порт Winbox (в примере — 30122).
Поместите правило ориентируясь на его номер в комментарии.
PoE out
Sub-menu: /interface ethernet poe
The console is used for accessing the MikroTik Router's configuration and management features using text terminals, either remotely using a serial port, telnet, SSH, console screen within WinBox, or directly using monitor and keyboard. The console is also used for writing scripts. This manual describes the general console operation principles. Please consult the Scripting Manual on some advanced console commands and on how to write scripts.
Console login options enable or disable various console features like color, terminal detection, and many other.
Additional login parameters can be appended to the login name after the '+' sign.
If the parameter is not present, then the default value is used. If the number is not present then the implicit value of the parameter is used.
Example: admin+c80w - will disable console colors and set terminal width to 80.
Param | Default | Implicit | Description |
---|---|---|---|
"w" | auto | auto | Set terminal width |
"h" | auto | auto | Set terminal height |
"c" | on | off | disable/enable console colors |
"t" | on | off | Do auto-detection of terminal capabilities |
"e" | on | off | Enables "dumb" terminal mode |
The login process will display the MikroTik banner and short help after validating the user name and password.
After the banner can be printed other important information, like system note set by another admin, the last few critical log messages, demo version upgrade reminder, and default configuration description.
For example, the demo license prompt and last critical messages are printed
At the end of the successful login sequence, the login process prints a banner that shows the command prompt, and hands over control to the user.
Default command prompt consists of user name, system identity, and current command path />
For example, change the current path from the root to the interface then go back to the root
Use up arrow to recall previous commands from command history, TAB key to automatically complete words in the command you are typing, ENTER key to execute the command, Control-C to interrupt currently running command and return to prompt and ? to display built-in help.
The easiest way to log out of the console is to press Control-D at the command prompt while the command line is empty (You can cancel the current command and get an empty line with Control-C, so Control-C followed by Control-D will log you out in most cases).
It is possible to write commands that consist of multiple lines. When the entered line is not a complete command and more input is expected, the console shows a continuation prompt that lists all open parentheses, braces, brackets, and quotes, and also trailing backslash if the previous line ended with backslash-white-space.
When you are editing such multiple line entries, the prompt shows the number of current lines and total line count instead of the usual username and system name.
Sometimes commands ask for additional input from the user. For example, the command ' /password ' asks for old and new passwords. In such cases, the prompt shows the name of the requested value, followed by colon and space.
The console allows the configuration of the router's settings using text commands. Since there is a lot of available commands, they are split into groups organized in a way of hierarchical menu levels. The name of a menu level reflects the configuration information accessible in the relevant section.
For example, you can issue the /ip route print command:
Instead of typing `/ip route` path before each command, the path can be typed only once to move into this particular branch of the menu hierarchy. Thus, the example above could also be executed like this:
Each word in the path can be separated by space (as in the example above) or by "/"
Notice that the prompt changes in order to reflect where you are located in the menu hierarchy at the moment. To move to the top level again, type " / "
To move up one command level, type " .. "
You can also use / and .. to execute commands from other menu levels without changing the current level:
Many of the command levels operate with arrays of items: interfaces, routes, users, etc. Such arrays are displayed in similarly-looking lists. All items in the list have an item number followed by flags and parameter values.
To change the properties of an item, you have to use the set command and specify the name or number of the item.
Планировщик: выключение (включение) интерфейса по времени
Выключите WiFi интерфейс wlan2-5GHz после 20:00:00, используя Планировщик MikroTik:
или выполните в терминале:
Включите WiFi интерфейс wlan2-5GHz с 08:00:00, используя Планировщик MikroTik:
или выполните в терминале:
Content
Article in other languages:
- 🇪🇸 – MikroTik: Cómo deshabilitar (habilitar) la interfaz en un horario
- 🇷🇺 – MikroTik: Как отключить (включить) интерфейс по расписанию
- 🇫🇷 – MikroTik: Comment désactiver (activer) l’interface selon un calendrier
- 🇩🇪 – MikroTik: So deaktivieren (aktivieren) Sie die Schnittstelle nach einem Zeitplan
- 🇳🇱 – MikroTik: Hoe de interface volgens een schema uit te schakelen (in te schakelen)
Блокируем Bruteforce
Правило «Bruteforce» — поместим IP адрес устройства в BlackList, при повторной неудачной попытке авторизации на устройстве.
При неудачной попытке авторизации MikroTik отправляет ответ с текстом «invalid user name or password» запросившему устройству.
Помещаем IP адрес устройства в BlackList, на 70 минут.
🟢 Защита MikroTik — базовая настройка безопасности, обсуждалось в этой статье. Я надеюсь, что теперь вы смогли настроить сервисы роутера и правила файрволла, улучшив защиту роутера MikroTik и устройств локальной сети. Однако, если вы столкнетесь с каким-то проблемами при настройке, не стесняйтесь написать в комментариях. Я постараюсь помочь.
Добавить скрипт в Планировщик
Для запуска скрипта необходимы разрешения: read, write, test, policy.
🟢 Как отключить или включить интерфейс MikroTik по расписанию или разрешить (запретить) доступ к интернету по времени, обсуждалось в этой статье. Надеюсь вы выбрали подходящий способ управления состоянием интерфейса. Однако, если вы столкнетесь с каким-то проблемами при настройке, не стесняйтесь написать в комментариях. Я постараюсь помочь.
Скрипт проверен: hAP ac lite [RouterBOARD 952Ui-5ac2nD], RouterOS 6.48.1 (stable).
We will analyze several ways to disable (enable) the MikroTik network interface or disable the Internet, according to a schedule: Firewall rule, NAT, MikroTik task scheduler or MikroTik script.
Сервисы
Изменить порт Winbox
Измените номер порта Winbox по умолчанию — 8291, на другой, свободный номер порта — Port (в примере порт 30122).
При изменении порта, следите чтобы не назначить Winbox порт используемый другой службой, список — здесь.
Scheduler: disable (enable) interface by time
Turn off WiFi wlan2-5GHz interface after 20:00:00 using MikroTik Scheduler:
Enable WiFi wlan2-5GHz interface from 08:00:00 using MikroTik Scheduler:
Обновление
В оборудовании MikroTik (как и в оборудовании других сетевых вендоров) периодически находят уязвимости — своевременное выполнение обновлений необходимая мера для обеспечения безопасности устройства.
Если обновление версии будет найдено, выполните обновление устройства.
🔗 Скрипт Проверка обновления RouterOS, пришлет уведомление о выходе новой версии прошивки.
NAT: how to allow (deny) the Internet on a schedule
You can deny (or allow) access to the Internet by time using the masquerade (NAT) rule setting.
Edit the masquerade rule, under the Extra tab:
Properties
- disabled - the interface will not use ARP
- enabled - the interface will use ARP
- local-proxy-arp - the router performs proxy ARP on the interface and sends replies to the same interface
- proxy-arp - the router performs proxy ARP on the interface and sends replies to other interfaces
- reply-only - the interface will only reply to requests originated from matching IP address/MAC address combinations which are entered as static entries in the ARP table. No dynamic entries will be automatically stored in the ARP table. Therefore for communications to be successful, a valid static entry must already exist.
- Note1: Auto-negotiation should not be disabled on one end only, otherwise Ethernet Interfaces may not work properly.
- Note2: Gigabit Ethernet and NBASE-T Ethernet links cannot work with auto-negotiation disabled.
Read-only properties
Property | Description |
---|---|
running (yes | no) | Whether interface is running. Note that some interface does not have running check and they are always reported as "running" |
slave (yes | no) | Whether interface is configured as a slave of another interface (for example Bonding) |
switch (integer) | ID to which switch chip interface belongs to. |
MikroTik скрипт: как отключить (включить) интерфейс
Выключать или включать интерфейс можно так же с помощью скрипта MikroTik и Планировщика заданий.
Отбросить недействительные пакеты
Правило «Drop Invalid Packet» — отбрасывает недействительные пакеты.
Помещаем правило после правила Trusted, в списке Filter Rules (поместите правило ориентируясь на его номер в комментарии).
Список «Внешние интерфейсы»
Помещаем в этот список внешние интерфейсы (интернет и т.д.).
Содержание
Отключить неиспользуемые сервисы
Отключаем сервисы MikroTik, которые не планируем использовать.
MikroTik script: how to disable (enable) the interface
You can also disable (or enable) the interface using the MikroTik script and the Task Scheduler.
Menu specific commands
Property | Description |
---|---|
blink ([id, name]) | Blink Ethernet leds |
monitor ([id, name]) | Monitor ethernet status. Read more>> |
reset-counters ([id, name]) | Reset stats counters. Read more>> |
reset-mac-address ([id, name]) | Reset MAC address to manufacturers default. |
cable-test (string) | Shows detected problems with cable pairs. Read More >> |
Создать скрипт
Укажите в скрипте следующие переменные:
- InterfaceName — имя интерфейса (в примере wlan2-5GHz);
- StartEnableTime — время начиная с которого интерфейс должен быть включен (в примере 08:00:00);
- EndEnableTime — время после которого интерфейс должен быть выключен (в примере 20:00:00).
Item Names
Some lists have items with specific names assigned to each of them. Examples are interface or user levels. There you can use item names instead of item numbers.
You do not have to use the print command before accessing items by their names, which, as opposed to numbers, are not assigned by the console internally, but are properties of the items. Thus, they would not change on their own. However, there are all kinds of obscure situations possible when several users are changing the router's configuration at the same time. Generally, item names are more "stable" than the numbers, and also more informative, so you should prefer them to numbers when writing console scripts.
Item Numbers
Item numbers are assigned by the print command and are not constant - it is possible that two successive print commands will order items differently. But the results of the last print commands are memorized and, thus, once assigned, item numbers can be used even after add, remove and move operations (since version 3, move operation does not renumber items). Item numbers are assigned on a per session basis, they will remain the same until you quit the console or until the next print command is executed. Also, numbers are assigned separately for every item list, so ip address print will not change the numbering of the interface list.
You can specify multiple items as targets to some commands. Almost everywhere, where you can write the number of items, you can also write a list of numbers.
There are some commands that are common to nearly all menu levels, namely: print, set, remove, add, find, get, export, enable, disable, comment, move . These commands have similar behavior throughout different menu levels.
Property | Description |
---|---|
add | This command usually has all the same arguments as a set, except the item number argument. It adds a new item with the values you have specified, usually at the end of the item list, in places where the order of items is relevant. There are some required properties that you have to supply, such as the interface for a new address, while other properties are set to defaults unless you explicitly specify them. |
- copy-from - Copies an existing item. It takes default values of a new item's properties from another item. If you do not want to make an exact copy, you can specify new values for some properties. When copying items that have names, you will usually have to give a new name to a copy
- place-before - places a new item before an existing item with a specified position. Thus, you do not need to use the move command after adding an item to the list
- disabled - controls disabled/enabled state of the newly added item(-s)
- comment - holds the description of a newly created item
- add command returns the internal number of items it has added
- the first argument specifies the item(-s) being moved.
- the second argument specifies the item before which to place all items being moved (they are placed at the end of the list if the second argument is omitted).
- from - show only specified items, in the same order in which they are given.
- where - show only items that match specified criteria. The syntax of where the property is similar to the find command.
- brief - forces the print command to use tabular output form
- detail - forces the print command to use property=value output form
- count-only - shows the number of items
- file - prints the contents of the specific sub-menu into a file on the router.
- interval - updates the output from the print command for every interval seconds.
- oid - prints the OID value for properties that are accessible from SNMP
- without-paging - prints the output without stopping after each screenful.
It is possible to switch between several input modes:
- Normal mode - indicated by normal command prompt.
- Safe mode - safe mode is indicated by the word SAFE after the command prompt. In this mode, the configuration is saved to disk only after the safe mode is turned off. Safe mode can be turned on/off with Ctrl+c or F4.Read more >>
- Hot-lock mode - indicated by additional yellow >. Hot-lock mode autocompletes commands and can be turned on/off with F7
There are two features in the console that help entering commands much quicker and easier - the [Tab] key completions, and abbreviations of command names. Completions work similarly to the bash shell in UNIX. If you press the [Tab] key after a part of a word, the console tries to find the command within the current context that begins with this word. If there is only one match, it is automatically appended, followed by a space:
/inte[Tab]_ becomes /interface _
If there is more than one match, but they all have a common beginning, which is longer than that what you have typed, then the word is completed to this common part, and no space is appended:
/interface set e[Tab]_ becomes /interface set ether_
If you've typed just the common part, pressing the tab key once has no effect. However, pressing it for the second time shows all possible completions in compact form:
The [Tab] key can be used almost in any context where the console might have a clue about possible values - command names, argument names, arguments that have only several possible values (like names of items in some lists or name of the protocol in firewall and NAT rules). You cannot complete numbers, IP addresses, and similar values.
Another way to press fewer keys while typing is to abbreviate command and argument names. You can type only the beginning of the command name, and, if it is not ambiguous, the console will accept it as a full name. So typing:
It is possible to complete not only the beginning, but also any distinctive sub-string of a name: if there is no exact match, the console starts looking for words that have string being completed as first letters of a multiple word name, or that simply contain letters of this string in the same order. If a single such word is found, it is completed at the cursor position. For example:
Console search allows performing keyword search through the list of RouterOS menus and the history. The search prompt is accessible with the [Ctrl+r] shortcut.
Разберем несколько способов отключить (включить) сетевой интерфейс MikroTik или отключить интернет, по расписанию: правило Firewall, NAT, планировщик заданий MikroTik или скрипт.
Разрешить ICMP
Правило «ICMP» — разрешает ICMP трафик на устройство.
Поместите правило ориентируясь на его номер в комментарии.
Читайте также: