[New version uploaded 3/26/2008. Fixed a bug which caused command output to hang sometimes, and added simple command line client]
Attached should be a ZIP with three files:
Mtik.pm - a simple perl client for the Mtik API. Pretty much a perl port of the python client from the Wiki, with an extra routine or two for formatting the returned data.
mtik_api_example.pl - an example of how to use the API. Provides some useful wireless ACL control routines. I've included enough comments so you should be able to work out how it all hangs together.
mtik_tty.pl - a simple command line client for testing API commands with. Use -h switch for usage info.
This code is very much a first cut. I intend to make the Mtik.pm stuff object oriented, so it can support more than one open Mtik connection at a time, but for now it is purely function driven. I needed it in a hurry!
Please feel free to feed back comments, suggestions, bug reports or light bulb jokes. Also feel free to modify, redistribute and generally do what you will with the code.
I think I've tracked down the reason it hangs occasionally on the socket recv. A misunderstanding on my part on how recv works with regards to specified read lengths.
I'm testing the new version, I'll post it when I'm sure it's fixed.
I've now built a fairly comprehensive provisioning system for our Mtik based wireless networks using it, and so far haven't had to update the main mtik_api.pl core.
If you feel adventurous, feel free to turn it into an actual package ...
Thanks for making this available: it has been a big help.
One mistake I made that other people who want to use it should avoid is the assumption that you can use the "talk" function just like you would a telnet connection. E.g., I tried something like:
Mtik::talk works fine for commands with no operands, but, if you're sending a command with keyword-based operands, you need to use the "mtik_cmd" function, and supply the operands in a hash, like the main loop in the example does. I think this is because mtik_cmd is doing the special formatting (like adding a leading "=" to operands) that's different between the terminal interface and the API.
The problem I'm having right now, though, is that I'm using the API to fiddle the firewall tables to provide temporary access to certain servers for users who've logged in through a web interface. I can add entries okay, now that I'm using mtik_cmd. But, when I try to remove entries with:
Code:
my @cmd = ("/ip/firewall/filter/remove", "$rowno"); my($retval,@results) = Mtik::talk(\@cmd);
The debug output says that the code is sending the command and operand, and I get a "!done" response. But the command doesn't remove the entry.
I'd kinda like to find out why this doesn't work, for future reference. Has anyone worked out a general-purpose method for sending commands with positional parameters?
Meanwhile, I found a hint in another posting that enabled me to make it work. It was about another command that takes a "row number" as a positional parameter in the telnet interface. In the API, the row is identified using the ".id" value passed back when listing the table (notthe row number that you'd use in the telnet interface), and a keyword of "numbers".
I have a function that uses the "talk" function to build an array of hashes containing the current firewall table, and another that will find the entry to be deleted. So the code to remove an entry looks like this:
[code]# Remove a camera/IPA pair from the firewall list. # Returns 0 if it was removed, or a negative number if it wasn't. # Inputs: # The camera resource name (which is also used as the name of # its chain in the firewall) # The source (i.e., user's) IP address sub mtik_access_remove { my($chain) = shift; my($ipa) = shift;
# First see whether it's already in the list my($rc, @firewall) = mtik_get_firewall; if ($rc) { return $rc; } my($rowno) = mtik_find_entry_in_firewall(\@firewall, $chain, $ipa); if ($rowno < 0) { print "IPA $ipa not found in chain $chain\n"; return -1; } # It's there, so try to remove it # my @cmd = ("/ip", "firewall", "filter", "remove", "$rowno"); my %operands; $operands{'numbers'} = $firewall[$rowno]{".id"}; my($retval,@results) = Mtik::mtik_cmd("/ip/firewall/filter/remove", \%operands); if ($retval != 1) { print "removal of IPA $ipa from $chain failed. RC = $retval\n$Mtik::error_msg\n"; return $retval; }
return 0; } [code]
Note the way I test $retval for a value of 1 (instead of 0) for "success". I translate it to 0 for code calling my functions, since I'm used to the convention of "0 for success, non-zero for failure".
Thanks again for sharing. I hope others find this record of my mistakes useful in avoiding repeating them.
Joined: Tue Feb 14, 2006 9:46 am Posts: 4811
Karma: 37
Location: Riga, Latvia
use .id to remove entries, in this case, do print and get a list of rules with .id numbers, then parse the result and get what rules you want to remove.
also when you add a rule, you get the .id number of the rule, so if in the same session you want to remove the rule you can use returned .id number of the rule to remove it in the end
use .id to remove entries, in this case, do print and get a list of rules with .id numbers, then parse the result and get what rules you want to remove.
also when you add a rule, you get the .id number of the rule, so if in the same session you want to remove the rule you can use returned .id number of the rule to remove it in the end
yes try to filter out a table of 1000 firewall rules, another 1000 of queues and another one of mangles, 1st your MT must be really fast, same as the machine you're running this script. It takes ages otherwise.
Also i checked, that id that you get returned when you add a rule, persist the same even after reboot, it only changes when you of course remove it . So if your doing some script for handling qos etc. It is good to keep those id's on some database such as Mysql then you just refer to id's you need, instead of parsing of hundreds of lines. besides that even if you have fast machines, such huge comunication (printing 5000 rules, and all ACKs in comunication) takes a lot of bandwidth. I'm doing such a database, and i always have at my hand script that when something goes wrong just does it in oldstyle way, removes all rules and add them again.
BTW. I saw that in ROUTEROS 3.13 something has changed becuase, usually my script worked but in this version the communication seems to be unregular, it looses some rules (in debug it shows "traped" instead of done). It runs smoothly on 3.10. There had to be some change. This what makes me always nervous at RouterOS, unpredictable changes.... that are not presented in changelog.
okay i've made an effort and debugged it, it seems that api dosen't accept src-port=445-65535, in fact it doesn't accept any range of ports for dst-port and src-port, this happens in ROS 3.11 and above... if I hashout directives with port-ranges my script works fine...
now it's your turn to fix or guide me how to overcome this
okay i have to give you back your honor, the problem was that MT got smarter in newer versions and can accept port ranges only for tcp and udp as far as i recall, and not giving parameter of protocol=tcp was the cause... and as far as i recall you mentioned this new behavior in changelog, soo I APOLOGIZE.
you never know how much frustating administrating can be ...
[New version uploaded 3/26/2008. Fixed a bug which caused command output to hang sometimes, and added simple command line client]
Attached should be a ZIP with three files:
Mtik.pm - a simple perl client for the Mtik API. Pretty much a perl port of the python client from the Wiki, with an extra routine or two for formatting the returned data.
mtik_api_example.pl - an example of how to use the API. Provides some useful wireless ACL control routines. I've included enough comments so you should be able to work out how it all hangs together.
mtik_tty.pl - a simple command line client for testing API commands with. Use -h switch for usage info.
This code is very much a first cut. I intend to make the Mtik.pm stuff object oriented, so it can support more than one open Mtik connection at a time, but for now it is purely function driven. I needed it in a hurry!
Please feel free to feed back comments, suggestions, bug reports or light bulb jokes. Also feel free to modify, redistribute and generally do what you will with the code.
Share And Enjoy.
-- hugh
Thanks for the code - but I would like to write that the read_len() function in mtapi.pl is completely wrong. For one byte lengths it works (but only by accident - the initial IF statement is not correct).
- the bitwise negation operator is not "!" but "~". If you use ! all nonzero values are repleced by zero and zero is replaced by 1 - bitwise AND has lower precedence than comparation (==). In original code two constants were compared and the result (mostly zero) was anded with $len - you have to read the subsequent bytes of block length using recv() not recursivelly calling read_len() again
This is the code which works for one and two byte lengths. I tried to correct others too but no checks/tests were made for them.
sub readbyte { my $line; $sock->recv($line,1); if ($debug > 4) { printf "readbyte:received: %x\n",ord($line); } return ord($line); };
This perl api need to be rewritten. It has also errors in general getting answer where !done= !trap= !fatal, -> sub talk and and sub read_sentence
I would like to thanks to the author. All my networks works managed using API Perl + PHP. api.perl gets statistics, signals, macs ap.php manage users,queues
Code:
sub read_sentence { my ($word); my ($i) = 0; my (@reply); my($retval) = 0; my($done) = 0; # tu trzeba dopisać obsluga trap while ($word = &read_word()) { if ($word =~ /^!done/) { $retval = 1; $done=1; } elsif ($word =~ /^!trap/) { $retval = 2; } elsif ($word =~ /^!fatal/) { $retval = 3; } $reply[$i++] = $word; if ($debug > 2) { print STDERR "MT: $word\n" } } return ($done,$retval,@reply); }
HELP ... i update all RB from 3.20 to 3.28 and some scripts in perl stops settings parameters - OK /interface/print - OK /interface/wireless/accesslist/print - OK
How many client stations is connected to this mikrotik? There is a bug which losts data when you try to get more then 1KB data. Try to change first doanloaded perl api and apply all canges on forum site in this thread.
How many client stations is connected to this mikrotik? There is a bug which losts data when you try to get more then 1KB data. Try to change first doanloaded perl api and apply all canges on forum site in this thread.
hmm .. many connected stations ... sometimes show 6 stations (maybe it is 1kB)
I try changed perl api but does't work fine - sometimes show 6 stations - sometimes crash
Hi I've been playing around allot with the perl API client, and have been testing a few commands on the TTY wrapper, however I'm having trouble trying to enable a defined queue in the simple queues table
what exact command do you try to set 'disabled' to false?..
I have a list of simple queue's that I wish to be able to disable and enable from a perl script using the API, /queue/simple-table/print will list the table of simple scripts, but my question is how do I enable the predefined scripts?
Basiclly i'm trying to setup a perl script that will enable a simple queue, then start the B/W server to create load on the link so I introduce latency on the link while I test an application communicating on a high latency link, Is the API able to control the BW server settings as well?
Joined: Tue Feb 14, 2006 9:46 am Posts: 4811
Karma: 37
Location: Riga, Latvia
/cancel is for commands that are continuous, and other way would not end ever, like:
Code:
/ip/address/print =interval=1
if you add .tag to continuous command then youcing /cancle with tag, you can cancel just this one command with the tag, and not all commands that are launched.
Also, API have no states, you send in commands and get responses. If you send more commands, you get more answers, if you run continuous command you will get answers all the time, but that does not mean you cannot send it more commands to get more responses.
Virtually speaking, if you want states then there are 2 that matter - you are either logged in (one state) or not (second state)
Users browsing this forum: Google [Bot] and 7 guests
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot post attachments in this forum