perl API client
RouterOS Scripting and API

83 posts   •   Page 1 of 2   •   1, 2
cheesegrits
just joined
 
Posts: 16
Joined: Fri Jun 01, 2007 11:17 pm

perl API client

by cheesegrits » Mon Mar 24, 2008 7:01 pm

[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

edit:
some other user added SSL functionality to this code. You can see it here (on this thread):
viewtopic.php?p=457584#p457584
Attachments
mtik_api2.zip
(4.75 KiB) Downloaded 4297 times
Last edited by cheesegrits on Thu Mar 27, 2008 12:12 am, edited 1 time in total.

cheesegrits
just joined
 
Posts: 16
Joined: Fri Jun 01, 2007 11:17 pm

Re: perl API client

by cheesegrits » Tue Mar 25, 2008 9:46 pm

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.

-- hugh

cheesegrits
just joined
 
Posts: 16
Joined: Fri Jun 01, 2007 11:17 pm

Re: perl API client

by cheesegrits » Thu Mar 27, 2008 12:13 am

New version uploaded. Bug described in previous post is fixed.

-- hugh

gacopl
Frequent Visitor
Frequent Visitor
 
Posts: 63
Joined: Sun Jul 29, 2007 5:11 pm
Location: Poland

Re: perl API client

by gacopl » Fri Apr 18, 2008 10:57 am

Hello

Thank you for doing this wrap for perl, however i cannot get it to run it gives me no socket: Connection refused :/

Please help

Michal

gacopl
Frequent Visitor
Frequent Visitor
 
Posts: 63
Joined: Sun Jul 29, 2007 5:11 pm
Location: Poland

Re: perl API client

by gacopl » Fri Apr 18, 2008 11:28 am

ok i solved i had to enable api service on MT

B/R
Michal

adamx
just joined
 
Posts: 1
Joined: Tue Jun 12, 2007 8:46 am

Re: perl API client

by adamx » Thu May 01, 2008 12:54 pm

Much appreciated. I'll have some additional contributions to this soon.

cheesegrits
just joined
 
Posts: 16
Joined: Fri Jun 01, 2007 11:17 pm

Re: perl API client

by cheesegrits » Fri May 09, 2008 10:23 pm

Glad it helps you out.

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 ... :)

-- hugh

ran_talbott
just joined
 
Posts: 2
Joined: Thu Apr 10, 2008 6:51 pm

Re: perl API client and non-keyword operands

by ran_talbott » Tue May 20, 2008 2:54 pm

Hugh,

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:

Code: Select all
@cmd = ("/category/command", "keyword1=value1", "keyword2=value2");
($rc, @response) = Mtik::talk(\@cmd);


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: Select all
    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.

Ran

User avatar
janisk
MikroTik Support
MikroTik Support
 
Posts: 5910
Joined: Tue Feb 14, 2006 10:46 am
Location: Riga, Latvia

Re: perl API client

by janisk » Tue May 27, 2008 4:10 pm

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

User avatar
normis
MikroTik Support
MikroTik Support
 
Posts: 19286
Joined: Fri May 28, 2004 11:04 am
Location: Riga, Latvia

Re: perl API client

by normis » Mon Jun 02, 2008 8:41 am

To cheesegrits: If you will add this info to the wiki, I will give you a free RouterOS license!
No answer to your question? How to write posts

cfernandes_io
just joined
 
Posts: 2
Joined: Fri May 30, 2008 5:22 pm

Re: perl API client

by cfernandes_io » Tue Jun 03, 2008 12:30 am

is possible to get a queue simple rate ?

k3dt
just joined
 
Posts: 15
Joined: Tue Jul 17, 2007 3:37 pm

Re: perl API client

by k3dt » Fri Jun 06, 2008 6:28 pm

Thank you very much for this scripts! Btw can somebody make php class for MT api?
//Czech Republic//

lagosta
just joined
 
Posts: 21
Joined: Sun May 11, 2008 10:02 pm

Re: perl API client

by lagosta » Wed Jul 09, 2008 1:02 am

Where should i put the pm file?
I'm running a kubuntu 7.10 distro.

gacopl
Frequent Visitor
Frequent Visitor
 
Posts: 63
Joined: Sun Jul 29, 2007 5:11 pm
Location: Poland

Re: perl API client

by gacopl » Tue Aug 26, 2008 1:56 am

janisk wrote: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.

B/R

Michal

BTW thx a lot for this perl wrap!!!

User avatar
janisk
MikroTik Support
MikroTik Support
 
Posts: 5910
Joined: Tue Feb 14, 2006 10:46 am
Location: Riga, Latvia

Re: perl API client

by janisk » Mon Sep 01, 2008 3:21 pm

would be nice if you wrote what exactly is failing, and how large outputs you are getting.

gacopl
Frequent Visitor
Frequent Visitor
 
Posts: 63
Joined: Sun Jul 29, 2007 5:11 pm
Location: Poland

Re: perl API client

by gacopl » Tue Dec 23, 2008 1:01 am

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 ;)

B/R
Michal

gacopl
Frequent Visitor
Frequent Visitor
 
Posts: 63
Joined: Sun Jul 29, 2007 5:11 pm
Location: Poland

Re: perl API client

by gacopl » Tue Dec 23, 2008 1:13 am

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 ... ;)

merry christmas

gacopl
Frequent Visitor
Frequent Visitor
 
Posts: 63
Joined: Sun Jul 29, 2007 5:11 pm
Location: Poland

Re: perl API client

by gacopl » Tue Dec 23, 2008 1:56 am

NO, unfortunately i was assuming things too quickly, i was right it itsn't accepting port ranges correctly:

root@ns1:/etc/lms# ./mtik_tty.pl -m 10.255.0.2 -u admin -p xxxxx
<<< /ip/firewall/mangle/add
<<< =chain=forward
<<< =protocol=tcp
<<< =src-port=445-460
<<<
>>> !trap
>>> =category=1
>>> =message=invalid value for argument range

like i said logging into 3.10 this works flawlessly, and in my script i have protocol=tcp directive so everything is fine from my side

B/R
Michal

gacopl
Frequent Visitor
Frequent Visitor
 
Posts: 63
Joined: Sun Jul 29, 2007 5:11 pm
Location: Poland

Re: perl API client

by gacopl » Fri Jan 30, 2009 5:55 pm

again it's not surprise to not get an answer here

shall i forward this to support?

dada
Member Candidate
Member Candidate
 
Posts: 171
Joined: Tue Feb 21, 2006 2:44 pm

Re: perl API client

by dada » Mon Feb 23, 2009 2:32 pm

cheesegrits wrote:[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);
};

sub read_len {
if ($debug > 4)
{
print "start read_len\n";
}
my $line;
my $len = readbyte();
if (($len & 0x80) == 0x00)
{
return $len;
}
elsif (($len & 0xC0) == 0x80)
{
$len &= ~0xC0;
$len <<= 8;
$len += readbyte();
}
elsif (($len & 0xE0) == 0xC0)
{
$len &= ~0xE0;
$len <<= 8;
$len += readbyte();
$len <<=8;
$len += readbyte();
}
elsif (($len & 0xF0) == 0xE0)
{
$len &= ~0xF0;
$len <<= 8;
$len += readbyte();
$len <<=8;
$len += readbyte();
$len <<=8;
$len += readbyte();
}
elsif (($len & 0xF8) == 0xF0)
{
$len = readbyte();
$len <<= 8;
$len += readbyte();
$len <<=8;
$len += readbyte();
$len <<=8;
$len += readbyte();
}
if ($debug > 4)
{
print "read_len got $len\n";
}
return $len;
}

Regards
Dalibor Toman

nodeny
just joined
 
Posts: 4
Joined: Sun May 03, 2009 4:06 am

Re: perl API client

by nodeny » Sun May 03, 2009 4:22 am

cheesegrits did you tested len>=0x200000?

I think
Code: Select all
print $sock chr(($len >> 8) & 0xFF);
print $sock chr(($len >> 8) & 0xFF);
print $sock chr(($len >> 8) & 0xFF);

...
will print one value. Maybe you mean

Code: Select all
print $sock chr(($len >> 24) & 0xFF);
print $sock chr(($len >> 16) & 0xFF);
print $sock chr(($len >> 8) & 0xFF);


yeah?

Then I read wiki.mikrotik.com/wiki/API:

len >= 0x10000000
0xF0 and len as four bytes


so your code is
Code: Select all
 elsif ($len < 0x10000000)
    {
        $len |= 0xE0000000;

0xE0000000 != 0xF000000000

and better elsif ($len < 0x10000000) -> else

The formula is seems simple. My code:

Code: Select all
$bytes=$len < 0x80? 1 : $len < 0x4000? 2 : $len < 0x200000? 3 : $len < 0x10000000? 4 : 5;
$len|=(0x0F >> (5-$bytes)) << ($bytes*8-$bytes+1);
while ($bytes--)
   {
    $str.=chr($len & 0xFF);
    $len>>=8;
   }


$str - rezult

nodeny
just joined
 
Posts: 4
Joined: Sun May 03, 2009 4:06 am

Re: perl API client

by nodeny » Sun May 03, 2009 4:27 am

I mean
Code: Select all
elsif ($len < 0x10000000)
...
elsif ($len < 0x10000000)

2 Identical conditions

nodeny
just joined
 
Posts: 4
Joined: Sun May 03, 2009 4:06 am

Re: perl API client

by nodeny » Sun May 03, 2009 11:38 am

Code: Select all
sub read_len
{
 my ($len,$c,$bytes);
 $sock->recv($c,1);
 $c=ord($c);
 $bytes=$c<0x80? 0 : $c<0xC0? 1 : $c<0xE0? 2 : $c<0xF0? 3 : 4;
 $len=$c & (0xFF >> $bytes);
 $bytes or return $len;
 while ($bytes--)
 {
    $sock->recv($c,1);
    $len=($len << 8) + ord($c);
 }
 return $len;
}

nodeny
just joined
 
Posts: 4
Joined: Sun May 03, 2009 4:06 am

Re: perl API client

by nodeny » Wed May 06, 2009 12:03 pm

Code: Select all
if ($word =~ /!done/)
{
    $retval = 1;
}


->

Code: Select all
if ($word =~ /^!done/)
{
    $retval = 1;
}


imagine a reply like that:

=name=system!done

User avatar
Chupaka
Forum Guru
Forum Guru
 
Posts: 7229
Joined: Mon Jun 19, 2006 11:15 pm
Location: Home Network Ltd., Minsk, Belarus

Re: perl API client

by Chupaka » Wed May 27, 2009 12:21 am

in API, you can use shortened value names, like in CLI; e.g.

/ip/route/print
=n=*1
=val=routing-mark

instead of

/ip/route/print
=numbers=*1
=value-name=routing-mark

isn't it a bit dangerous? maybe it should be forbidden, to avoid possible future problems? API is not CLI for humans...
For every complex problem, there is a solution that is simple, neat, and wrong.

¡ɹǝ|SOɹǝʇnoɹ ʞıʇoɹʞıW ɯ‚|

MikroTik. Your life. Your routing.

skype: pavel.skuratovich

User avatar
janisk
MikroTik Support
MikroTik Support
 
Posts: 5910
Joined: Tue Feb 14, 2006 10:46 am
Location: Riga, Latvia

Re: perl API client

by janisk » Mon Jun 01, 2009 11:07 am

users have to use full command/attribute names when writing API command. Shortened names will not be allowed in 3.25+ versions

User avatar
normis
MikroTik Support
MikroTik Support
 
Posts: 19286
Joined: Fri May 28, 2004 11:04 am
Location: Riga, Latvia

Re: perl API client

by normis » Mon Jun 01, 2009 11:09 am

What's new in 3.25:

*) api - do not accept truncated property names;
No answer to your question? How to write posts

User avatar
Chupaka
Forum Guru
Forum Guru
 
Posts: 7229
Joined: Mon Jun 19, 2006 11:15 pm
Location: Home Network Ltd., Minsk, Belarus

Re: perl API client

by Chupaka » Mon Jun 01, 2009 11:31 am

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

¡ɹǝ|SOɹǝʇnoɹ ʞıʇoɹʞıW ɯ‚|

MikroTik. Your life. Your routing.

skype: pavel.skuratovich

User avatar
normis
MikroTik Support
MikroTik Support
 
Posts: 19286
Joined: Fri May 28, 2004 11:04 am
Location: Riga, Latvia

Re: perl API client

by normis » Mon Jun 01, 2009 11:33 am

yes, thank you very much for the report :) will you come to MUM in USA?
No answer to your question? How to write posts

User avatar
Chupaka
Forum Guru
Forum Guru
 
Posts: 7229
Joined: Mon Jun 19, 2006 11:15 pm
Location: Home Network Ltd., Minsk, Belarus

Re: perl API client

by Chupaka » Mon Jun 01, 2009 11:46 am

unfortunately, no - it's too expensive for me =(
I'll wait for the next MUM in Europe, CZ MUM was the best ))

during your MUM in USA I'll be looking for such issues with API here, in Minsk :D
For every complex problem, there is a solution that is simple, neat, and wrong.

¡ɹǝ|SOɹǝʇnoɹ ʞıʇoɹʞıW ɯ‚|

MikroTik. Your life. Your routing.

skype: pavel.skuratovich

Pikoro
Frequent Visitor
Frequent Visitor
 
Posts: 62
Joined: Fri Mar 14, 2008 11:43 am

Re: perl API client

by Pikoro » Sat Jul 11, 2009 6:47 am

When are you guys going to have a MUM in Japan?

User avatar
ema
just joined
 
Posts: 20
Joined: Mon Apr 14, 2008 5:13 pm
Location: Poland, Warsaw

Re: perl API client

by ema » Wed Jul 15, 2009 11:58 am

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: Select all
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);
}

######## PUBLIC FUNCTIONS ############

sub talk
{
    #my(@sentence) = shift;
    my($sentence_ref) = shift;
    my(@sentence) = @$sentence_ref;
    &write_sentence(\@sentence);
    my(@reply);
    my(@attrs);
    my($i) = 0;
    my($retval) = 0;
    my($done) = 0;
    while (($done,$retval,@reply) = &read_sentence())
    {
        foreach my $line (@reply)
        {
            if ($line =~ /^=(\S+)=(.*)/)
            {
                $attrs[$i]{$1} = $2;
            }
        }
        if ($retval > 0 && $done>0)
        {
            last;
        }
       
        $i++;
    }
    return ($retval, @attrs);
}


gumis78
just joined
 
Posts: 2
Joined: Thu Sep 17, 2009 2:23 pm

Re: perl API client

by gumis78 » Thu Sep 17, 2009 2:30 pm

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

but

/interface/wireless/registration-table/print - CRASH

what is wrong ??

help me ...
Krzys

User avatar
ema
just joined
 
Posts: 20
Joined: Mon Apr 14, 2008 5:13 pm
Location: Poland, Warsaw

Re: perl API client

by ema » Sun Sep 20, 2009 11:02 pm

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.

User avatar
janisk
MikroTik Support
MikroTik Support
 
Posts: 5910
Joined: Tue Feb 14, 2006 10:46 am
Location: Riga, Latvia

Re: perl API client

by janisk » Tue Sep 22, 2009 12:16 pm

if i remember correctly then first releases of Perl API lacked support for long responses. Do as ema said

gumis78
just joined
 
Posts: 2
Joined: Thu Sep 17, 2009 2:23 pm

Re: perl API client

by gumis78 » Tue Sep 22, 2009 2:48 pm

ema wrote: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

zlyZwierz
newbie
 
Posts: 33
Joined: Tue Jun 19, 2007 2:37 pm
Location: Poland

Re: perl API client

by zlyZwierz » Tue Sep 22, 2009 5:00 pm

Maybe check mine perl API packege: http://zwierzu.zepsul.net/Mtik.pm.txt

sample code:

Code: Select all
#!/usr/bin/perl

use strict;
use warnings;
use Mtik;
use Data::Dumper;


       my $mt = Mtik->new( host => 'host', user => 'admin', pass => 'pass');

        if ($mt->login()) {
            my $regtable_api = $mt->get_by_key('/interface/wireless/registration-table/print','=stats', 'mac-address');
            print Dumper $regtable_api;
        }



Works for me..

Code: Select all
localhost sbin # perl dupa.pl

$VAR1 = {
          '00:15:6D:D0:0F:F5' => {
                                   'rx-ccq' => '17',
                                   'hw-frame-bytes' => '42100172,7240063',
                                   'packets' => '49461,38274',
                                   'nstreme' => 'false',
                                   'ack-timeout' => '28',
                                   'uptime' => '08:03:54',
                                   'interface' => 'wlan3',
                                   'last-activity' => '00:00:03.350',
                                   'frame-bytes' => '40615897,6306238',
                                   'mac-address' => '00:15:6D:D0:0F:F5',
                                   'framing-mode' => 'none',
                                   '802.1x-port-enabled' => 'true',
                                   'routeros-version' => '3.2',
                                   'ap' => 'false',
                                   'bytes' => '40910305,6535882',
                                   'signal-to-noise' => '34',
                                   'tx-ccq' => '97',
                                   'radio-name' => 'Motozbyt',
                                   'frames' => '49461,38274',
                                   'hw-frames' => '49738,38665',
                                   'tx-frames-timed-out' => '0',
                                   'compression' => 'false',
                                   'wmm-enabled' => 'false',
                                   'p-throughput' => '18146',
                                   'tx-signal-strength' => '-67',
                                   'wds' => 'false',
                                   'signal-strength' => '-70dBm@6Mbps',
                                   'comment' => '',
                                   '.id' => '*4',
                                   'rx-rate' => '12Mbps',
                                   'strength-at-rates' => '-70dBm@6Mbps 1s350ms,-70dBm@9Mbps 18s380ms,-71dBm@12Mbps 3s350ms,-71dBm@18Mbps 3m39s750ms,-72dBm@24Mbps 3m43s620ms',
                                   'tx-rate' => '24Mbps'
                                 },

grealish
just joined
 
Posts: 10
Joined: Tue Apr 07, 2009 6:43 pm

Re: perl API client

by grealish » Tue Sep 29, 2009 11:38 am

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
Code: Select all
/queue/simple-table/print
#lists queues
>>> !re
>>> =.id=*2
>>> =name=limit-vlan3-tc
>>> =target-addresses=192.168.192.0/22
>>> =dst-address=0.0.0.0/0
>>> =interface=vlan3-192.168.192.0/22 VM TC
>>> =parent=none
>>> =direction=both
>>> =priority=8
>>> =queue=default-small/default-small
>>> =limit-at=0/0
>>> =max-limit=2M/2M
>>> =burst-limit=0/0
>>> =burst-threshold=0/0
>>> =burst-time=0s/0s
>>> =total-queue=default-small
>>> =bytes=0/0
>>> =total-bytes=0
>>> =packets=0/0
>>> =total-packets=0
>>> =dropped=0/0
>>> =total-dropped=0
>>> =rate=0/0
>>> =total-rate=0
>>> =packet-rate=0/0
>>> =total-packet-rate=0
>>> =queued-packets=0/0
>>> =total-queued-packets=0
>>> =queued-bytes=0/0
>>> =total-queued-bytes=0
>>> =lends=0/0
>>> =total-lends=0
>>> =borrows=0/0
>>> =total-borrows=0
>>> =pcq-queues=0/0
>>> =total-pcq-queues=0
>>> =disabled=true
>>> =invalid=false
>>> =dynamic=false
>>> !done


When I specify the =.id=*2 and then =disable=false it returns
>>> !done
<<<
>>> !trap
>>> =message=no such command prefix

And i'm unsure if i'm specifying this right
Thanks in advance

User avatar
Chupaka
Forum Guru
Forum Guru
 
Posts: 7229
Joined: Mon Jun 19, 2006 11:15 pm
Location: Home Network Ltd., Minsk, Belarus

Re: perl API client

by Chupaka » Tue Sep 29, 2009 12:22 pm

/queue/simple-table ?..

what exact command do you try to set 'disabled' to false?..
For every complex problem, there is a solution that is simple, neat, and wrong.

¡ɹǝ|SOɹǝʇnoɹ ʞıʇoɹʞıW ɯ‚|

MikroTik. Your life. Your routing.

skype: pavel.skuratovich

grealish
just joined
 
Posts: 10
Joined: Tue Apr 07, 2009 6:43 pm

Re: perl API client

by grealish » Tue Sep 29, 2009 12:31 pm

Chupaka wrote:/queue/simple-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?

User avatar
Chupaka
Forum Guru
Forum Guru
 
Posts: 7229
Joined: Mon Jun 19, 2006 11:15 pm
Location: Home Network Ltd., Minsk, Belarus

Re: perl API client

by Chupaka » Tue Sep 29, 2009 12:45 pm

at first, '/queue/simple-table/print' gets
Code: Select all
no such command prefix
trap =) you should use '/queue/simple/print'

for enabling, use
Code: Select all
/queue/simple/set
=.id=*2
=disabled=false
For every complex problem, there is a solution that is simple, neat, and wrong.

¡ɹǝ|SOɹǝʇnoɹ ʞıʇoɹʞıW ɯ‚|

MikroTik. Your life. Your routing.

skype: pavel.skuratovich

grealish
just joined
 
Posts: 10
Joined: Tue Apr 07, 2009 6:43 pm

Re: perl API client

by grealish » Tue Sep 29, 2009 3:36 pm

Chupaka wrote:at first, '/queue/simple-table/print' gets
Code: Select all
no such command prefix
trap =) you should use '/queue/simple/print'

for enabling, use
Code: Select all
/queue/simple/set
=.id=*2
=disabled=false


Cool Thanks, works now, however can I address the queue differently as in;
Code: Select all
<<< /queue/simple/set
<<< =name=limit-vlan3-tc
<<< =disable=false
<<<
>>> !done


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?

User avatar
Chupaka
Forum Guru
Forum Guru
 
Posts: 7229
Joined: Mon Jun 19, 2006 11:15 pm
Location: Home Network Ltd., Minsk, Belarus

Re: perl API client

by Chupaka » Tue Sep 29, 2009 4:08 pm

grealish wrote:Cool Thanks, works now, however can I address the queue differently as in;
Code: Select all
<<< /queue/simple/set
<<< =name=limit-vlan3-tc
<<< =disable=false
<<<
>>> !done



no, you should first find necessary item, then disable it by id. like this:

Code: Select all
/queue/simple/print
=.proplist=.id
?name=limit-vlan3-tc


and then

Code: Select all
/queue/simple/set
=.id=*here's_your_id
=disabled=false


grealish wrote:Is the API able to control the BW server settings as well?


basically, API can do anything you can do with CLI =) all exceptions you can get to know only after you try to do something unusual =)
For every complex problem, there is a solution that is simple, neat, and wrong.

¡ɹǝ|SOɹǝʇnoɹ ʞıʇoɹʞıW ɯ‚|

MikroTik. Your life. Your routing.

skype: pavel.skuratovich

grealish
just joined
 
Posts: 10
Joined: Tue Apr 07, 2009 6:43 pm

Re: perl API client

by grealish » Tue Sep 29, 2009 6:45 pm

thanks, so I do as is, however it returns idone?? is it not to return the .id? of the name I passed?
Code: Select all
<<< /queue/simple/print
<<< =.proplist=.id
<<< ?name=limit-vlan3=tc
<<<
>>> !done

User avatar
Chupaka
Forum Guru
Forum Guru
 
Posts: 7229
Joined: Mon Jun 19, 2006 11:15 pm
Location: Home Network Ltd., Minsk, Belarus

Re: perl API client

by Chupaka » Tue Sep 29, 2009 9:09 pm

checked with 3.28: when that name exists, the request returns the following:
Code: Select all
!re=
=.id=*1
For every complex problem, there is a solution that is simple, neat, and wrong.

¡ɹǝ|SOɹǝʇnoɹ ʞıʇoɹʞıW ɯ‚|

MikroTik. Your life. Your routing.

skype: pavel.skuratovich

grealish
just joined
 
Posts: 10
Joined: Tue Apr 07, 2009 6:43 pm

Re: perl API client

by grealish » Tue Sep 29, 2009 9:17 pm

Chupaka wrote:checked with 3.28: when that name exists, the request returns the following:
Code: Select all
!re=
=.id=*1


Got it :)
<<< /queue/simple/print
<<< =.proplist=.id
<<< ?name=limit-vlan3-tc
<<<
>>> !re
>>> =.id=*2
>>> !done
<<<

Will try now to implement this in a perl script

I believe you have to enter the tree structure with the /cancel followed by two CR/LF before it will reset the state of the API?

User avatar
Chupaka
Forum Guru
Forum Guru
 
Posts: 7229
Joined: Mon Jun 19, 2006 11:15 pm
Location: Home Network Ltd., Minsk, Belarus

Re: perl API client

by Chupaka » Tue Sep 29, 2009 9:31 pm

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

¡ɹǝ|SOɹǝʇnoɹ ʞıʇoɹʞıW ɯ‚|

MikroTik. Your life. Your routing.

skype: pavel.skuratovich

User avatar
janisk
MikroTik Support
MikroTik Support
 
Posts: 5910
Joined: Tue Feb 14, 2006 10:46 am
Location: Riga, Latvia

Re: perl API client

by janisk » Thu Oct 01, 2009 10:48 am

/cancel is for commands that are continuous, and other way would not end ever, like:

Code: Select all
/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)

milanc
just joined
 
Posts: 7
Joined: Sat May 22, 2010 5:20 pm

Re: perl API client

by milanc » Sun Aug 21, 2011 4:58 pm

Hi, i have problem.
Is possible get via api UPS status? Command is /system ups monitor 0 once

This is ok...
Code: Select all
my $ret = $mt->get_by_key('/system/ups/print');
print Dumper($ret);

$VAR1 = {
          '*3' => {
                    'nominal-battery-voltage' => '24',
                    'disabled' => 'false',
                    'manufacture-date' => '08/06/99',
                    'serial' => '************',
                    'version' => '50.11.I',
                    'model' => 'SMART-UPS 700',
                    'name' => 'ups1',
                    'alarm-setting' => 'immediate',
                    'port' => 'serial0',
                    'min-runtime' => '5m',
                    'on-line' => 'true',
                    '.id' => '*3',
                    'offline-time' => '00:05:00',
                    'load' => '5',
                    'invalid' => 'false'
                  }
        };

my $ret = $mt->get_by_key('/system/ups/monitor','=0','=once');
print Dumper($ret);

$VAR1 = {};


what is wrong? Thanks for help.
Milan

User avatar
Chupaka
Forum Guru
Forum Guru
 
Posts: 7229
Joined: Mon Jun 19, 2006 11:15 pm
Location: Home Network Ltd., Minsk, Belarus

Re: perl API client

by Chupaka » Mon Aug 22, 2011 1:22 pm

try
Code: Select all
my $ret = $mt->get_by_key('/system/ups/monitor','=.id=*3','=once=');
For every complex problem, there is a solution that is simple, neat, and wrong.

¡ɹǝ|SOɹǝʇnoɹ ʞıʇoɹʞıW ɯ‚|

MikroTik. Your life. Your routing.

skype: pavel.skuratovich

  Next
83 posts   •   Page 1 of 2   •   1, 2

Who is online

Users browsing this forum: No registered users and 5 guests

It is currently Wed Nov 26, 2014 12:48 am