Mikrotik script error no such item

Script error no such item Thu May 12, 2016 11:01 pm Searching in http://wiki.mikrotik.com/wiki/Manual:Scripting I could not find the meaning of «no such item» that I sometimes get in scripts and which aborts the script. 1. What’s the meaning of that message? 2. Why does it abort a script? In the mean time I’m […]

Содержание

  1. Script error no such item
  2. Re: Wat’s the meaning of «no such item» and why does it terminate a script?
  3. Re: Wat’s the meaning of «no such item» and why does it terminate a script?
  4. Re: Wat’s the meaning of «no such item» and why does it terminate a script?
  5. Script error no such item
  6. Re: no such item (4) — FQDN address-list find where comment=X
  7. Re: no such item (4) — FQDN address-list find where comment=X
  8. Re: no such item (4) — FQDN address-list find where comment=X
  9. Re: no such item (4) — FQDN address-list find where comment=X
  10. Re: no such item (4) — FQDN address-list find where comment=X
  11. Re: no such item (4) — FQDN address-list find where comment=X
  12. Re: no such item (4) — FQDN address-list find where comment=X
  13. Script error no such item
  14. Re: Bug: No such item(4) or object doesn’t exist (4)
  15. Re: Bug: No such item(4) or object doesn’t exist (4)
  16. Re: Bug: No such item(4) or object doesn’t exist (4)
  17. Re: Bug: No such item(4) or object doesn’t exist (4)
  18. Re: Bug: No such item(4) or object doesn’t exist (4)
  19. MikroTik.by
  20. Ошибка в скрипте назначение интерфейсов
  21. Ошибка в скрипте назначение интерфейсов
  22. Re: Ошибка в скрипте назначение интерфейсов
  23. Re: Ошибка в скрипте назначение интерфейсов
  24. Re: Ошибка в скрипте назначение интерфейсов
  25. Re: Ошибка в скрипте назначение интерфейсов
  26. Re: Ошибка в скрипте назначение интерфейсов
  27. Re: Ошибка в скрипте назначение интерфейсов
  28. Script error no such item

Script error no such item

Thu May 12, 2016 11:01 pm

Searching in http://wiki.mikrotik.com/wiki/Manual:Scripting I could not find the meaning of «no such item» that I sometimes get in scripts and which aborts the script.

1. What’s the meaning of that message?
2. Why does it abort a script?

In the mean time I’m going to track down where in the script it terminates.

There are some Google Search results, but to me they’re not conclusive: https://www.google.com/search?q=mikrotik+»no+such+item»

Re: Wat’s the meaning of «no such item» and why does it terminate a script?

Fri May 13, 2016 10:38 am

Re: Wat’s the meaning of «no such item» and why does it terminate a script?

Fri May 13, 2016 5:54 pm

What do you mean with `etc.`? Can you be more specific? Are there examples that show this going wrong at will? (i.e. reproducible cases).

Re: Wat’s the meaning of «no such item» and why does it terminate a script?

Fri May 13, 2016 7:39 pm

To be more precise, menu specific «get» and «set» commands (be it «/interface get», «/interface set», «/queue simple get», «/queue simple set», «/ip arp get», «/ip arp set», etc.) throw this error when you give a non existent ID or name as value for the «number(s)» argument.

If a queue with name «test» existed, then the command will return the queue * (as an associative array with each property being array key, and the corresponding value being the member’s value).

But if there is no queue with the name «test» at the time the command is actually called, the error is thrown.

If an item (be it a queue, an interface, an ARP item. anything, at any menu) is dynamically generated, and is suddenly removed, you could end up in situations where in one second, a «print» at the menu would tell you the item exists, and a second later, it won’t.

An example of dynamically generated items are for example queues, which can be generated from various places, such as the «/ip hotspot» menu — you set up queues for each logged in user, and the queue gets created when the user logs in, and gets removed when the user logs out. Any scripts that do something while the user is logged in may end up in a situation where they attempt to do something, but in the middle of it, the user logs out, causing any future get/set calls related to them to fail.

* Wrong. Sorry. The above would error that you need to specify a property to retrieve. You must specify that as a second argument, at which point the command returns the value of the specified property. The point about the error being thrown when the item doesn’t exist is still valid, but my description of «get» was utterly wrong.

Источник

Script error no such item

Fri May 01, 2020 7:33 am

And my mailbox get spammed with notifications about no such item (4) script error randomly. Every few minutes (during that time those instructions are called several hundreds or maybe even thousands times). I verified that script always crashes on one of those two lines.

I know this error is due to fact that ROS is «forgetting» some dynamiic entries during script execution but thiis is basically single, atomic instruction. How can I do some workaround? My goal is to get list of IPs that ROS resolved fqdn based address-lists to (script is basically flushing DNS cache and removing all dynamic entries forcing ROS to resolve address-lists again whenever there’s some synchronization issue between. Synchronization is checked by performing manual DNS resolution against specified server and comparison every 2 seconds)

Re: no such item (4) — FQDN address-list find where comment=X

Fri May 01, 2020 9:01 am

This can be how ROS handles subroutines. Without showing the whole script its not easy to see what is wrong.

Add the whole script in and cut and past it to command line to run i directly.
Using :put everywhere to see output as script goes along.

Use Splunk> to log/monitor your MikroTik Router(s). See link below.

Re: no such item (4) — FQDN address-list find where comment=X

Fri May 01, 2020 10:12 am

This can be how ROS handles subroutines. Without showing the whole script its not easy to see what is wrong.

Add the whole script in and cut and past it to command line to run i directly.
Using :put everywhere to see output as script goes along.

I did that. I mean not exactly that but I put :log debug message=N where N was some number and I put it every line, then I browsed through syslog logs to see after which log script stops and throws «no such item (4)» and like I said it’s always one of those 2 lines.

Here’s full script (just without those debug logs to not spam):

Re: no such item (4) — FQDN address-list find where comment=X

Fri May 01, 2020 11:22 am

Its som hard to debug such a big script.

If you wrap the script in <> and past it to the terminal, its easier to see where things go wrong.
Same with put instead of log. All on screen when things are running.

Also split the scripts up in parts and cut/past part by part to terminal.

What version is your RouterOS? It may be a bug and other version works better.
I do see other have had similar problems: viewtopic.php?t=139518 viewtopic.php?t=115391

It may be that the table are to large and some is change in beweeen when script are running so things get lost and gives error.
I do see that they suggest to use foreach

Use Splunk> to log/monitor your MikroTik Router(s). See link below.

Re: no such item (4) — FQDN address-list find where comment=X

Fri May 01, 2020 11:32 am

Your issue probably is that some of your DNS-derived address list items have really short TTL (like when you try to get addresses of CDN servers in an address list), and there is a reasonable chance that your find retrieves a list of items where some of them expire some milliseconds later and the next usage indicates that they are missing.
One would indeed expect that for a single command line this «cannot happen», but on the other hand it is good that the router uses multitasking and address list expiry can happen simultaneously with script execution. You would not want to block the expiry during any execution of a script.

I agree with you that there should be some way to catch those errors, preferably just using on-error= or otherwise by setting some mode where such errors are just ignored for the script.

Re: no such item (4) — FQDN address-list find where comment=X

Sat May 02, 2020 1:56 am

Your issue probably is that some of your DNS-derived address list items have really short TTL (like when you try to get addresses of CDN servers in an address list), and there is a reasonable chance that your find retrieves a list of items where some of them expire some milliseconds later and the next usage indicates that they are missing.
One would indeed expect that for a single command line this «cannot happen», but on the other hand it is good that the router uses multitasking and address list expiry can happen simultaneously with script execution. You would not want to block the expiry during any execution of a script.

I agree with you that there should be some way to catch those errors, preferably just using on-error= or otherwise by setting some mode where such errors are just ignored for the script.

Yeah, I don’t want to just skip sending alerts about script errors because while this script is not really all that mission critical there are other script on router that monitor various aspects of network and they’re more stateful so error in them could leave script in «undefined behavior» state and may require manual cleanup. It doesn’t happen often but once every few weeks. Now this one script is spamming my mailbox with «no such item (4)» errors and I don’t know which errors are from this one and which are from more important scripts :/

I already filed «bug request» to mikrotik if they could maybe at least add in log indication which script crashed, and even better in which line — this way I could just set up filter in mailbox to ignore crashes of this one particular script that is not really all that critical.

Re: no such item (4) — FQDN address-list find where comment=X

Sat May 02, 2020 9:23 am

I do agree that RouterOS is no good to debug. IF some stops, it should log a line telling where and what failed.
At least on-error should pick this up so that the sctipt does not stop.
I do see that this problem has been around for 10 years+ viewtopic.php?t=26893

You need to make a script that test if some is there before trying to change/delete it.

Use Splunk> to log/monitor your MikroTik Router(s). See link below.

Re: no such item (4) — FQDN address-list find where comment=X

Sat May 02, 2020 10:49 am

With «I agree with you that there should be some way to catch those errors, preferably just using on-error= or otherwise by setting some mode where such errors are just ignored for the script.» of course I mean that this ignore action is only for the current script or current function in a script, not globally.
The on-error= clause is already local. It is unfortunate that this does not catch the «no such item» error, that is imho a bug that should be fixed.
There are other topics on the forum where people encounter unpredictable «no such item» errors (due to race conditions) and cannot handle them in a reasonable way.

Источник

Script error no such item

Fri Aug 10, 2018 4:31 pm

We found a bug in recent RouterOS versions (> 6.38) where sometimes disabled objects are not found by Winbox or Scripts.

As you can see in the attached print, sometimes when you try to enable a disabled tunnel you get a «object doesn’t exist» message. After two or three attemps it’s successfully enabled.

The same happens on scripts. But the message is slight different (no such item(4)). Again, we had to put a retry logic on theses steps in order to avoid these errors.

Re: Bug: No such item(4) or object doesn’t exist (4)

Tue Aug 14, 2018 6:20 pm

Hi, I’ve experienced the same issue after update to 6.42.6 from 6.40.4. It seems I’ve found a way to get rid of that bug.
What did I do:
— disabled and renamed ppp interace in question
— created the new one with exactly the same config and original name
— got a current config in text (export file=test)
— carefully searched for all references to renamed interface inside text config (by means of find) and replaced corresponding configuration items
to new interface with original name in winbox. That includes filter, nat, routing, led and traffic flow settings for me.
— enabled new interface and removed renamed one.

Not that much time passed since I do that, but for now I’ve never seen that problem again.

Re: Bug: No such item(4) or object doesn’t exist (4)

Mon Sep 17, 2018 3:06 pm

The same situation in 6.40.9 (bugfix)
[admin@MikroTik-Agg] /routing ospf interface> print
Flags: X — disabled, I — inactive, D — dynamic, P — passive
# INTERFACE COST PRIORITY NETWORK-TYPE AUTHENTICATION AUTHENTICATION-KEY
0 D 10 1 point-to-point none
1 DP Loopback-Backbone 10 1 broadcast none
2 D 10 1 point-to-point none
[admin@MikroTik-Agg] /routing ospf interface> set cost=100 0
no such item (4)
[admin@MikroTik-Agg] /routing ospf interface> set cost=100 1
no such item (4)
[admin@MikroTik-Agg] /routing ospf interface> set cost=100 2
no such item (4)
[admin@MikroTik-Agg] /routing ospf interface>

Re: Bug: No such item(4) or object doesn’t exist (4)

Mon Sep 17, 2018 4:28 pm

Re: Bug: No such item(4) or object doesn’t exist (4)

Mon Sep 24, 2018 1:08 pm

Re: Bug: No such item(4) or object doesn’t exist (4)

Mon Sep 24, 2018 1:28 pm

I’ve repeatedly seen cases where order of parameters did matter, so the ID had to follow the set immediately, although in most cases it is identified by context.

So try the following:

/routing ospf interface set 0 cost=100
/routing ospf interface set 1 cost=100
/routing ospf interface set 2 cost=100

Another point is that if the list changes in the meantime between print and issuing the command, the «user IDs» assigned to the internal references by the print lose validity (this is best visible with the /ip firewall connection elements)

Источник

MikroTik.by

For every complex problem, there is a solution that is simple, neat, and wrong.

Ошибка в скрипте назначение интерфейсов

Ошибка в скрипте назначение интерфейсов

Сообщение mmm » 04 окт 2018, 12:00

Re: Ошибка в скрипте назначение интерфейсов

Сообщение Chupaka » 04 окт 2018, 12:06

Re: Ошибка в скрипте назначение интерфейсов

Сообщение mmm » 04 окт 2018, 13:16

Вот такая петрушка!

Re: Ошибка в скрипте назначение интерфейсов

Сообщение Chupaka » 04 окт 2018, 14:35

Re: Ошибка в скрипте назначение интерфейсов

Сообщение mmm » 04 окт 2018, 15:17

Re: Ошибка в скрипте назначение интерфейсов

Сообщение Chupaka » 04 окт 2018, 19:14

В общем, раньше в скриптах всё, что использовало команду print, работало кое-как и не всегда, а сейчас, видимо, это вообще на всякий случай закрыли

Полотенце сильно большое, чтобы с наскоку разобраться, чего же оно там хочет. Если просто найти последний интерфейс на роутере — то можно сделать как-то так:

Re: Ошибка в скрипте назначение интерфейсов

Сообщение mmm » 05 окт 2018, 11:11

Источник

Script error no such item

на форуме англоязычном у многих есть мелкие проблемы, днём читал на работе, там уже
было постов 90. Частично разработчики что-то ответили, одних просили прислать логи,
и дебаг-файл, другим сказали, что что-то поправят снова в будущих версиях.
Но когда делают большие обновления и есть минимум 10-20 у которых что-то уже
не то, уже повод обождать.
Также обратите внимание на параметры в окне Ресурсы: а именно на кол-во
записанных секторов и на кол-во всего
записанных секторов.
Данные значения у людей на прошивке 6.47 растут достаточно быстро.

Пару визуальных проверок сделали, и если грубо, то параметр «Total Sector Writes»
на старой прошивке за 30 дней примерно показал параметр в 417 тысяч, на новой
прошивке этот показатель равен 1,5 миллиону за 52 минуты аптайма.
Я не говорю что это плохо, но память, в микротике, NAND, и что с ней там делают.

2300 перезаписаных секторов, при этом есть устройство которое не обновил, другой модели (750g3), но тоже как свич и даже чуть больше, там конфиг изредка меняется, там за 14 дней аптайма 36000, явно что-то не так.
З.Ы. Глянул на старичка RB751U-2HnD которого тоже обновил, там за 3 часа 1200 и на hAP за то же время 1100.

У меня на двух 951Ui-2nD за двое суток всего 5700

Источник

Проблема со скриптом, бьюсь уже неделю не могу понять причину проблемы.

Есть скрипт на удаление соединения sip:

Код: Выделить всё

:local pingcount "4";
:local pingip "8.8.8.8";
:local voiceGwIp "10.1.2.250:5060";
:local replyHost;
:local gateway;   
:local gatewayDn;
:local activeReply;
:local activeRoute;
:local routeDn;
:local voiceCon;

:local pingresult [/ping $pingip count=$pingcount];
:if ($pingresult > 0) do={
    :set activeRoute [/ip route find where active routing-mark=tel];
    :if ($activeRoute = "") do={
        :local mes1 "Clear-sip-connections: route is not found.";
    }  
    :set routeDn [/ip route find where routing-mark=dn];
    :if ($routeDn = "") do={
        :local mes2 "Clear-sip-connections: route Dn is not found.";
    }  
    :set voiceCon [/ip firewall connection find where src-address=$voiceGwIp];
    :if ($voiceCon = "") do={
        :local mes3 "Clear-sip-connections: connection is not found.";
    }
    :if (($activeRoute != "" ) && ($routeDn != "" ) && ($voiceCon != "" )) do={
        :set gateway [/ip route get $activeRoute gateway];   
        :set gatewayDn  [/ip route get $routeDn gateway];
        :set activeReply [/ip firewall connection get $voiceCon reply-dst-address];
         
        :if ($gateway = $gatewayDn) do={
            :set replyHost "xxx.xxx.xxx.xxx:5060";
        } else={
            :set replyHost "yyy.yyy.yyy.yyy:5060";
        }
        :if ($activeReply != $replyHost) do={
            /ip firewall connection remove $voiceCon;
            :log warning ("Clear-sip-connections: clearing connection src-address:$voiceGwIp, reply-dst-address:$activeReply"); 
        } else={
            :nothing;
        }
    } else={
        :log warning ("$mes1 $mes2 $mes3");
    }
} else={    
    :log warning ("Clear-sip-connections: no ping");
}

Скрипт сам по себе работает (запускается через планировщик каждые 30 сек.), соединение убивает, но иногда в лог пишет «script error: no such item (4)».
Выяснил, что проблема происходит на этом участке:

Код: Выделить всё

:set voiceCon [/ip firewall connection find where src-address=$voiceGwIp];

Но почему он иногда выдает ошибку понять не могу, так это соединение висит постоянно, к тому же пробовал задавать заведомо неверный src-address, на выходе получаю пустой результат.
Версия системы 6.6.

Проблема со скриптом, бьюсь уже неделю не могу понять причину проблемы.

Есть скрипт на удаление соединения sip:

:local pingcount "4";
:local pingip "8.8.8.8";
:local voiceGwIp "10.1.2.250:5060";
:local replyHost;
:local gateway;   
:local gatewayDn;
:local activeReply;
:local activeRoute;
:local routeDn;
:local voiceCon;

:local pingresult [/ping $pingip count=$pingcount];
:if ($pingresult > 0) do={
   :set activeRoute [/ip route find where active routing-mark=tel];
   :if ($activeRoute = "") do={
       :local mes1 "Clear-sip-connections: route is not found.";
   }  
   :set routeDn [/ip route find where routing-mark=dn];
   :if ($routeDn = "") do={
       :local mes2 "Clear-sip-connections: route Dn is not found.";
   }  
   :set voiceCon [/ip firewall connection find where src-address=$voiceGwIp];
   :if ($voiceCon = "") do={
       :local mes3 "Clear-sip-connections: connection is not found.";
   }
   :if (($activeRoute != "" ) && ($routeDn != "" ) && ($voiceCon != "" )) do={
       :set gateway [/ip route get $activeRoute gateway];   
       :set gatewayDn  [/ip route get $routeDn gateway];
       :set activeReply [/ip firewall connection get $voiceCon reply-dst-address];

       :if ($gateway = $gatewayDn) do={
           :set replyHost "xxx.xxx.xxx.xxx:5060";
       } else={
           :set replyHost "yyy.yyy.yyy.yyy:5060";
       }
       :if ($activeReply != $replyHost) do={
           /ip firewall connection remove $voiceCon;
           :log warning ("Clear-sip-connections: clearing connection src-address:$voiceGwIp, reply-dst-address:$activeReply"); 
       } else={
           :nothing;
       }
   } else={
       :log warning ("$mes1 $mes2 $mes3");
   }
} else={    
   :log warning ("Clear-sip-connections: no ping");
}

Скрипт сам по себе работает (запускается через планировщик каждые 30 сек.), соединение убивает, но иногда в лог пишет «script error: no such item (4)».

Выяснил, что проблема происходит на этом участке:

:set voiceCon [/ip firewall connection find where src-address=$voiceGwIp];

Но почему он иногда выдает ошибку понять не могу, так это соединение висит постоянно, к тому же пробовал задавать заведомо неверный src-address, на выходе получаю пустой результат.

Версия системы 6.6.


Изменено 6 декабря, 2013 пользователем Art_isT

  • edinorog

Mikrotik RouterOS v6.17
железка 2011UiAS-2HnD

строка из скрипта

:local InterfaceISP2Address [/ip address get [find interface=ether2] address]

Если интерфейсу не присвоен адрес (обрыв связи, проблема с dhcp сервером, др проблемы) то скрипт выдает «no such item» и дальше не выполняется.

Как заставить выполнять скрипт дальше, несмотря на «no such item»?


  • Вопрос задан

    более трёх лет назад

  • 3690 просмотров

Например, вот так:

:local interfaceName "ether2"
:local InterfaceISP2Address 

:if ([ :len [ /interface find name=$interfaceName ] ] = 0 ) do={
    :log warning "[SCRIPT_NAME] No interface '$interfaceName' was found, please do check updater script configuration."
    :set InterfaceISP2Address "0.0.0.0/0"
} else={
    # Get current IP address for the interface
    :set InterfaceISP2Address [ :tostr [ /ip address get [/ip address find interface=$interfaceName] address ] ]
}

Попробуйте как-то так:

:if ( [/ip address find interface=ether2 ] != "" ) do={
 :local InterfaceISP2Address [/ip address get [find interface=ether2] address];
}

Удачи!

Пригласить эксперта


  • Показать ещё
    Загружается…

10 февр. 2023, в 00:15

1000 руб./в час

09 февр. 2023, в 22:06

500 руб./за проект

09 февр. 2023, в 22:01

50000 руб./за проект

Минуточку внимания

Правила форума
Как правильно оформить вопрос.
Прежде чем начать настройку роутера, представьте, как это работает. Попробуйте почитать статьи об устройстве интернет-сетей. Убедитесь, что всё, что Вы задумали выполнимо вообще и на данном оборудовании в частности.
Не нужно изначально строить Наполеоновских планов. Попробуйте настроить простейшую конфигурацию, а усложнения добавлять в случае успеха постепенно.
Пожалуйста, не игнорируйте правила русского языка. Отсутствие знаков препинания и неграмотность автора топика для многих гуру достаточный повод проигнорировать топик вообще.

1. Назовите технологию подключения (динамический DHCP, L2TP, PPTP или что-то иное)
2. Изучите темку «Действия до настройки роутера».
viewtopic.php?f=15&t=2083
3. Настройте согласно выбранного Вами мануала
4. Дочитайте мануал до конца и без пропусков, в 70% случаев люди просто не до конца читают статью и пропускают важные моменты.
5. Если не получается, в Winbox открываем терминал и вбиваем там /export hide-sensitive. Результат в топик под кат, интимные подробности типа личных IP изменить на другие, пароль забить звездочками.
6. Нарисуйте Вашу сеть, рисунок (схему) сюда. На словах может быть одно, в действительности другое.

Luser

Сообщения: 5
Зарегистрирован: 13 сен 2017, 11:38

Здравствуйте уважаемые знатоки, прошу вашей помощи в написании скрипта.

Задача: При подключении пользователя к OVPN, исходя из имени клиента, отправить пакет WakeOnLan на сопоставленный mac-адрес.
Как я себе это представляю: в PPP профиле OVPN разместить скрипт в секции «On Up»
В чем проблема: не могу понять как присвоить переменную из вывода команды: ppp active print «ИМЯ клиента»

Аватара пользователя

podarok66

Модератор
Сообщения: 4225
Зарегистрирован: 11 фев 2012, 18:49
Откуда: МО

03 июл 2019, 11:06

Из принта ничего не присвоите. Из get или из find берите. Там главное дать чёткие признаки. Вот пример из рабочей машинки. Но это если один такой туннель

Код: Выделить всё

:put [ppp active get [/ppp active find service=sstp] name]

Если много, надо найти уникальный признак для каждого, который будет определять однозначный поиск.

Мануалы изучил и нигде не ошибся? Фаервол отключил? Очереди погасил? Витая пара проверена? … Тогда Netinstal’ом железку прошей и настрой ее заново. Что, все равно не фурычит? Тогда к нам. Если не подскажем, хоть посочувствуем…

Luser

Сообщения: 5
Зарегистрирован: 13 сен 2017, 11:38

03 июл 2019, 11:59

ver. 6.43.12
решил так:

Код: Выделить всё

:local OPVNNameClient [/ppp active get [find name="ТоЧтоИщу"] name]; :if ($OPVNNameClient = "ТомуЧтоНужно") do {/system script run "ИмяСкриптаWOLдляКлиента"};

только приходится для каждого имени писать, хорошо бы все циклом устроить…

Последний раз редактировалось Luser 03 июл 2019, 19:32, всего редактировалось 1 раз.

Luser

Сообщения: 5
Зарегистрирован: 13 сен 2017, 11:38

03 июл 2019, 14:20

исполнение вашего кода завершается ошибкой: invalid internal item number

KARaS’b

Сообщения: 1199
Зарегистрирован: 29 сен 2011, 09:16

03 июл 2019, 16:43

Luser писал(а): ↑

03 июл 2019, 10:13


Здравствуйте уважаемые знатоки, прошу вашей помощи в написании скрипта.

Задача: При подключении пользователя к OVPN, исходя из имени клиента, отправить пакет WakeOnLan на сопоставленный mac-адрес.
Как я себе это представляю: в PPP профиле OVPN разместить скрипт в секции «On Up»
В чем проблема: не могу понять как присвоить переменную из вывода команды: ppp active print «ИМЯ клиента»

Если пользователей не много, то для каждого можно забиндить интерфейс и в профиле указать уникальный профайл (предварительно создать), в котором уже указать то что вы хотите делать при поднятии интерфейса, т.е. тупо строчку с готовой командой на посыл WOL пакета.

Аватара пользователя

podarok66

Модератор
Сообщения: 4225
Зарегистрирован: 11 фев 2012, 18:49
Откуда: МО

03 июл 2019, 16:57

Luser писал(а): ↑

03 июл 2019, 14:20


исполнение вашего кода завершается ошибкой: invalid internal item number

Блин, ну естественно. Я же сказал, что это просто пример из рабочей машинки. Я посмотрел имя, использовав в качестве признака в поиске имя сервиса. При другом признаке, например адресе клиента, будет работать поиск нормально.
И что вы там на жалобу жмёте? Вам нужно потревожить модератора? Так вот он я. Не трогайте эту кнопку по пустякам.

Мануалы изучил и нигде не ошибся? Фаервол отключил? Очереди погасил? Витая пара проверена? … Тогда Netinstal’ом железку прошей и настрой ее заново. Что, все равно не фурычит? Тогда к нам. Если не подскажем, хоть посочувствуем…

Luser

Сообщения: 5
Зарегистрирован: 13 сен 2017, 11:38

03 июл 2019, 17:24

Спасибо всем за помощь. Жалобу видимо случайно нажал (трудности перевода), прошу извинить. А насчет команды с «рабочей машинки» я указал service=pptp, он был поднят. Я никогда не использовал скрипты в mikrotik, поэтому и обратился сюда на форум.

Код: Выделить всё

:put [ppp active get [/ppp active find service=pptp] name]

invalid internal item number: Разобрался…ошибка возникла т.к. было 2 активных pptp соединения…

Аватара пользователя

podarok66

Модератор
Сообщения: 4225
Зарегистрирован: 11 фев 2012, 18:49
Откуда: МО

03 июл 2019, 20:34

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

Код: Выделить всё

tool wol mac=XX:XX:XX:XX:XX:XX interface=pptp

и как бы всё. Или там для каждого профиля разный интерфейс будет? Не соображу сейчас. Пробуйте, если что, смоделируем ситуацию и изменим скрипт.

Мануалы изучил и нигде не ошибся? Фаервол отключил? Очереди погасил? Витая пара проверена? … Тогда Netinstal’ом железку прошей и настрой ее заново. Что, все равно не фурычит? Тогда к нам. Если не подскажем, хоть посочувствуем…

Luser

Сообщения: 5
Зарегистрирован: 13 сен 2017, 11:38

08 июл 2019, 23:40

Помогите разобраться почему не работает код и не определяет переменную.
Есть активный пользователь в PPP, отображаю в терминале:

Код: Выделить всё

:put  [/ppp active get [find name="Client1"] name];
Client1

Пытаюсь написать скрипт проверки всех по имени:
/system script run «MyScript»
с таким содержимым:

Код: Выделить всё

{
{
:local NameClientOVPN [/ppp active get [find name="Client1"] name]; 
:if ($NameClientOVPN = "Client1") do {/system script run "WOL PC1"};
}
{ 
:local NameClientOVPN [/ppp active get [find name="Client2"] name]; 
:if ($NameClientOVPN = "Client2") do {/system script run "WOL PC2"};
}
}

На что получаю: no such item
В другом варианте:
/system script run «MyScript1»

Код: Выделить всё

:local NameClientOVPN [/ppp active get [find name="Client1"] name]; :if ($NameClientOVPN = "Client1") do {/system script run "WOL PC1"};
:local NameClientOVPN [/ppp active get [find name="Client2"] name]; :if ($NameClientOVPN = "Client2") do {/system script run "WOL PC2"};
no such item

ИСПРАВИЛ:

Код: Выделить всё

foreach A in=[/ppp active get [/ppp active find service=ovpn] name] do={
  if ($A="Client1") do={
    /system script run "WOL PC1"
  }
  if ($A="Client2") do={
    /system script run "WOL PC2"
  }
}

mister

Сообщения: 2
Зарегистрирован: 23 май 2022, 13:40

23 май 2022, 13:50

Luser писал(а): ↑

08 июл 2019, 23:40


Помогите разобраться почему не работает код и не определяет переменную.
Есть активный пользователь в PPP, отображаю в терминале:

Код: Выделить всё

:put  [/ppp active get [find name="Client1"] name];
Client1

Пытаюсь написать скрипт проверки всех по имени:
/system script run «MyScript»
с таким содержимым:

Код: Выделить всё

{
{
:local NameClientOVPN [/ppp active get [find name="Client1"] name]; 
:if ($NameClientOVPN = "Client1") do {/system script run "WOL PC1"};
}
{ 
:local NameClientOVPN [/ppp active get [find name="Client2"] name]; 
:if ($NameClientOVPN = "Client2") do {/system script run "WOL PC2"};
}
}

На что получаю: no such item
В другом варианте:
/system script run «MyScript1»

Код: Выделить всё

:local NameClientOVPN [/ppp active get [find name="Client1"] name]; :if ($NameClientOVPN = "Client1") do {/system script run "WOL PC1"};
:local NameClientOVPN [/ppp active get [find name="Client2"] name]; :if ($NameClientOVPN = "Client2") do {/system script run "WOL PC2"};
no such item

ИСПРАВИЛ:

Код: Выделить всё

foreach A in=[/ppp active get [/ppp active find service=ovpn] name] do={
  if ($A="Client1") do={
    /system script run "WOL PC1"
  }
  if ($A="Client2") do={
    /system script run "WOL PC2"
  }
}

Хорошее решение, но так не работает!
версия OS:6.48
А хотелось бы)
Работает вот так:
foreach A in=[/ppp active get [find name=Client1] name] do={
if ($A=»Client1″) do={
/system script run «Client1»
}
if ($A=»Client2″) do={
/system script run «WOL PC2»
}
}

Ошибка в скрипте назначение интерфейсов

mmm

Сообщения: 12
Зарегистрирован: 04 окт 2018, 11:39

Ошибка в скрипте назначение интерфейсов

Доброго времени суток! Ошибка возникла после обновления routeros до 6.42.7 скрипт писал не я и о данунгрейте речи быть не может. Помогите разобраться, собственно сам скрипт:

Код: Выделить всё

### INT ###
$ipCONF iptmp=($config->3)
:global ether1NAME [/interface ethernet get [ find default-name="ether1" ] name ]
:global ether1 {ip="$ip";netmask="$prefix";gateway=($network+1)}
$ipCONF iptmp=($config->4)
:global ether5NAME [/interface ethernet get ($intCOUNT-1) name]
:global ether5 {ip="$ip";netmask="$prefix";gateway=($network+3)}
:if ( $MODE != "vsat" and $intCOUNT="5" ) do={
	/interface ethernet set [find name="$ether5NAME" ] name="ether$intCOUNT-$ISP5" master-port=none
	:set ether5NAME [/interface ethernet get ($intCOUNT-1) name]
	}
$ipCONF iptmp=($config->5)
:global lanNAME [/ip address get [find network="192.168.88.0"] interface ]
:global lan {ip=($network+1);netmask="$prefix";network="$network";pool="$poolSTART-$poolEND"}
$ipCONF iptmp=($config->6)
:global l2tpNAME "l2tp-$ORG"
:global l2tp {network=($network+1)}
$ipCONF iptmp=($config->7)
:global greNAME "gre-$ORG"
:global gre {ip=($network+2);netmask="$prefix";network="$network"}

собственно ошибка:

Код: Выделить всё

[[email protected]] /ip address> :if ( $MODE != "vsat" and $intCOUNT="5" ) do={
{... /interface ethernet set [find name="$ether5NAME" ] name="ether$intCOUNT-$ISP5" master-port=none
expected end of command (line 2 column 80)

Спасибо!

Аватара пользователя

Chupaka

Сообщения: 3631
Зарегистрирован: 29 фев 2016, 15:26
Откуда: Минск
Контактная информация:

Re: Ошибка в скрипте назначение интерфейсов

Сообщение

Chupaka » 04 окт 2018, 14:35

В скриптах обращаться к интерфейсам по номеру нельзя, результат непредсказуемый. А судя по первому посту, переменная intCOUNT у вас вообще не инициализируется, поэтому я даже угадать затрудняюсь, что там должно происходить…

Аватара пользователя

Chupaka

Сообщения: 3631
Зарегистрирован: 29 фев 2016, 15:26
Откуда: Минск
Контактная информация:

Re: Ошибка в скрипте назначение интерфейсов

Сообщение

Chupaka » 04 окт 2018, 19:14

В общем, раньше в скриптах всё, что использовало команду print, работало кое-как и не всегда, а сейчас, видимо, это вообще на всякий случай закрыли :)

Полотенце сильно большое, чтобы с наскоку разобраться, чего же оно там хочет. Если просто найти последний интерфейс на роутере — то можно сделать как-то так:

Код: Выделить всё

:global ether5NAME [/interface ethernet get ($intCOUNT-1) name]

заменить на

Код: Выделить всё

:local i5; :foreach i in=[/interface ethernet find] do={ :set i5 $i }; :global ether5NAME [/interface ethernet get $i5 name];

, а

Код: Выделить всё

:set ether5NAME [/interface ethernet get ($intCOUNT-1) name]

— на

Ну и использовать global-переменные в таком количестве без надобности — тоже так себе подход…

mmm

Сообщения: 12
Зарегистрирован: 04 окт 2018, 11:39

Re: Ошибка в скрипте назначение интерфейсов

Сообщение

mmm » 05 окт 2018, 11:11

День добрый Chupaka! ошибок при заливке скрипта нет но результат нулевой. По идее скрип должен отключить дефолтную конфигурацию и выдать новый ИП этого почему то не происходит. После перезагрузки адрес не получаю a Neighbors пишет что 192.168.88.1. Хэлп!!!!!

mmm

Сообщения: 12
Зарегистрирован: 04 окт 2018, 11:39

Re: Ошибка в скрипте назначение интерфейсов

Сообщение

mmm » 05 окт 2018, 12:11

мои действия:
-New terminal
-копипаст скрипта
-reboot
и….вуаля микротик должен работать но на деле после перезагрузки ИП адрес не получаю a Neighbors пишет что 192.168.88.1

Аватара пользователя

Chupaka

Сообщения: 3631
Зарегистрирован: 29 фев 2016, 15:26
Откуда: Минск
Контактная информация:

Re: Ошибка в скрипте назначение интерфейсов

Сообщение

Chupaka » 05 окт 2018, 13:34

Ну, команда, добавляющая LAN-адрес — вот тут:

Код: Выделить всё

/ip address {
	remove [find address="$lanIP$lanMASK"]
	add address="$lanIP$lanMASK" interface="$lanNAME"

Можно вывести в Терминал, что же она пытается добавить:

Код: Выделить всё

/ip address {
	:put "Adding $lanIP$lanMASK";
	remove [find address="$lanIP$lanMASK"]
	add address="$lanIP$lanMASK" interface="$lanNAME"

И посмотреть, что именно он в этот момент добавляет.

mmm

Сообщения: 12
Зарегистрирован: 04 окт 2018, 11:39

Re: Ошибка в скрипте назначение интерфейсов

Сообщение

mmm » 06 окт 2018, 09:24

Код: Выделить всё

MMM      MMM       KKK                          TTTTTTTTTTT      KKK
  MMMM    MMMM       KKK                          TTTTTTTTTTT      KKK
  MMM MMMM MMM  III  KKK  KKK  RRRRRR     OOOOOO      TTT     III  KKK  KKK
  MMM  MM  MMM  III  KKKKK     RRR  RRR  OOO  OOO     TTT     III  KKKKK
  MMM      MMM  III  KKK KKK   RRRRRR    OOO  OOO     TTT     III  KKK KKK
  MMM      MMM  III  KKK  KKK  RRR  RRR   OOOOOO      TTT     III  KKK  KKK

  MikroTik RouterOS 6.43.2 (c) 1999-2018       http://www.mikrotik.com/

Последний раз редактировалось mmm 07 окт 2018, 13:15, всего редактировалось 1 раз.

Аватара пользователя

Chupaka

Сообщения: 3631
Зарегистрирован: 29 фев 2016, 15:26
Откуда: Минск
Контактная информация:

Re: Ошибка в скрипте назначение интерфейсов

Сообщение

Chupaka » 06 окт 2018, 12:57

Прячьте код под тег [code]

Вижу, в новой версии комментарий «default configuration» сменили на «defconf», поэтому 192.168.88.1 у вас не выключается, хотя 172…. добавился нормально. Измените комментарий в скрипте.

mmm

Сообщения: 12
Зарегистрирован: 04 окт 2018, 11:39

Re: Ошибка в скрипте назначение интерфейсов

Сообщение

mmm » 06 окт 2018, 14:55

Ничего я не менял! :-( и «defconf» в скрипте не нашел, к сожалению
менять здесь?

Код: Выделить всё

/ip dhcp-server {
	:local o [find name="default" ]
	:if ([:len $o] != 0) do={ remove $o }
	}
/ip pool {
	:local o [find name="default-dhcp"]
	:if ([:len $o] != 0) do={ remove $o }

Понравилась статья? Поделить с друзьями:
  • Mikrotik openvpn tls error
  • Mikrotik no route to host ошибка как исправить
  • Mikrotik memory system error critical
  • Mikrotik lte1 mbim error sms store is full
  • Mikrotik last disconnect reason port error