MikroTik::API(3)

πŸ“¦
version 2.0.1 Β· 2 versions
, in fedora 43

🌸 MikroTik::API β€” client to MikroTik RouterOS API 🌸

ok bestie, sit down, hydrate, because we're about to talk about MikroTik::API πŸ’… this is a Perl client for the MikroTik RouterOS API, and it comes to you straight from the User Contributed Perl Documentation (section 3, so you already know it's a library and not some little command you run in your shell, iykyk πŸŽ€).


✨ VERSION ✨

Version 2.0.1

⚠️ CAUTION: Dependencies change with version 2.0.0. MikroTik::API now relies on Moo instead of Moose. Please be sure, dependencies are met before upgrading. (fr fr, check your deps before you upgrade, she switched her whole personality at 2.0.0 😭)

🌈 SYNOPSIS 🌈

here's the whole thing in one glorious look:

use MikroTik::API;

my $api = MikroTik::API->new({
    host => 'mikrotik.example.org',
    username => 'whoami',
    password => 'SECRET',
    use_ssl => 1,
});

my ( $ret_get_identity, @aoh_identity ) = $api->query( '/system/identity/print', {}, {} );
print "Name of router: $aoh_identity[0]->{name}\n";

$api->logout();

like… she connects, she asks the router what her name is, she says bye. main character energy from start to finish πŸ‘‘


πŸ’œ DESCRIPTION πŸ’œ

this section is literally empty in the original, and honestly? we respect the silence 🫢


🫢 PUBLIC METHODS 🫢

new( \%config )

ok so this is how you bring her into the world:

my $api = MikroTik::API->new({
    host => 'mikrotik.example.org',
    username => 'whoami',
    password => 'SECRET',
    autoconnect => 1, # optional (set to 0 if you do not want to connect during construction, default: 1)
    use_ssl => 1, # optional (0 for non ssl / 1 for ssl)
    port => 8729, # optonal (needed if you use another port then 8728 for non-ssl or 8729 for ssl)
    debug => 0, # optional (set beween 0 (none) and 5 (most) for debug messages)
    timeout => 3, # optional (timeout after 3 seconds during connect)
    probe_before_talk => 3, # optional (probe connection before each actual command)
    reconnect_after_failed_probe => 1, # optional (reconnect if probe failed)

});

(yes, optonal and beween are spelled exactly like that in the original, and no, we are not fixing them, they're iconic πŸ’€)

$api->connect()

Connect happens on construction if you provide host address. that's the whole tea. but if you'd rather do it by hand:

my $api = MikroTik::API->new();

$api->set_host('mikrotik.example.org');
$api->set_port(1234);
$api->set_use_ssl(1);

$api->connect();

$api->login()

Connect happens on construction if you provide host address, username and password. so if you handed over all three up front, she's already logged in and you don't gotta do anything. if not:

my $api = MikroTik::API->new({ host => 'mikrotik.example.org' });

$api->set_username('whoami');
$api->set_password('SECRET');

$api->login();

$api->logout()

the polite goodbye πŸ₯Ή

$api->logout();

$api->cmd( $command, \%attributes )

this is the do the thing method. watch her work:

# Set with no key required
# /system identity set name=MyNewMikroTik
my $returnvalue = $api->cmd( '/system/identity/set', { 'name' => 'MyNewMikroTik' } );
print "Name set\n" if ($returnvalue < 2);

# Set keyed on the name "local"
# /interface bridge set local fast-forward=no
my $returnvalue = $api->cmd( '/interface/bridge/set', { '.id' => 'local', 'fast-forward' => 'no' } );
print "Bridge fast-forward turned off\n" if ($returnvalue < 2);

# Set keyed on internal key
# /interface bridge set *cc fast-forward=no
my $returnvalue = $api->cmd( '/interface/bridge/set', { '.id' => '*cc', 'fast-forward' => 'no' } );
print "Bridge fast-forward turned off\n" if ($returnvalue < 2);

# Reset a value
# /routing bgp peer set testpeer !keepalive-time
my $returnvalue = $api->cmd( '/routing/bgp/peer/set', { '.id' => 'testpeer', 'keepalive-time' => undef } );
print "Reset keepalive-time on testpeer\n" if ($returnvalue < 2);

notice that undef value in the last one? that's the "reset this" move. it's giving !keepalive-time 🧚

$api->query( $command, \%attributes, \%conditions )

the reading method. this one returns a return value plus a list of hashrefs (aoH, as the kids say):

# Get all interfaces of type ether
my ( $ret_interface_print, @interfaces ) = $api->query('/interface/print', { '.proplist' => '.id,name' }, { type => 'ether' } );
foreach my $interface ( @interfaces ) {
    print "$interface->{name}\n";
}

# get all default routes that don't have the dynamic attribute
my ( $ret_route_print, @routes ) = $api->query('/ip/route', { '.proplist' => '.id,dst-address' }, { 'dst-address' => '0.0.0.0/0', 'dynamic'=>undef } );
foreach my $route ( @routes ) {
    print "$route->{'dst-address'}\n";
}

# get all default routes that don't have the dynamic attribute (alternate using array ref)
my ( $ret_route_print, @routes ) = $api->query('/ip/route', { '.proplist' => '.id,dst-address' }, [ 'dst-address=0.0.0.0/0', '-dynamic' ] );
foreach my $route ( @routes ) {
    print "$route->{'dst-address'}\n";
}

# get all default routes along with those with the dynamic attribute (note 'or' operator as last arg)
my ( $ret_route_print, @routes ) = $api->query('/ip/route', { '.proplist' => '.id,dst-address' }, [ 'dst-address=0.0.0.0/0', 'dynamic', '#|' ] );
foreach my $route ( @routes ) {
    print "$route->{'dst-address'}\n";
}

so you got hashref conditions, arrayref conditions, a - prefix for "not this", and '#|' as the last arg when you want an or instead of an and. lowkey elegant, highkey useful πŸ’…

$api->get_by_key( $command, $keycolumn )

want your results keyed by a column instead of a boring old array? say less:

my %interface = $api->get_by_key('/interface/ethernet/print', 'name' );
print "$interface{'ether1'}->{running}\n";

πŸŽ€ ACCESSORS πŸŽ€

  • $api->get_host(), $api->set_host( $hostname ) β€” get/set the host. yes bestie, it's a getter and a setter in one bullet, she's efficient.
  • $api->get_port(), $api->set_port( $portnumber ) β€” get/set the port number.
  • $api->get_username(), $api->set_username( $username ) β€” get/set the username.
  • $api->get_password(), $api->set_password( $password ) β€” get/set the password.
  • $api->get_use_ssl(), $api->set_use_ssl( $zero_or_one ) β€” get/set SSL usage, as a 0 or 1.
  • $api->get_ssl_verify(), $api->set_ssl_verify( $zero_or_one ) β€” get/set SSL verification, as a 0 or 1.
  • $api->get_autoconnect(), $api->set_autoconnect( $zero_or_one ) β€” get/set autoconnect, as a 0 or 1.

$api->get_new_auth_method(), $api->set_new_auth_method( $zero_or_one )

🚫 DEPRECATED: does not have any effect any longer. Login looks up wether new method is possible and falls back to old method. This parameter will be removed in future. Auth method changed in RouterOS v6.43+ (https://wiki.mikrotik.com/wiki/Manual:API#Initial_login) and reduces login by one call but sends password in plaintext.

so like… she decides for herself now, and this knob is just decorative. also bestie, note the plaintext password part, that's not a cute look πŸ”₯

$api->get_socket(), $api->set_socket( $io_socket )

If you need to use an existing socket for the API connection.

my $socket = IO::Socket::INET->new();
$api->set_socket( $socket );

$api->get_debug(), $api->set_debug( $int )

$api->set_debug(0); # no debug
$api->set_debug(5); # verbose debug to STDOUT

$api->get_timeout(), $api->set_timeout( $seconds )

Abort connect after $seconds of no reply from MikroTik. This _will not_ affect lost connections. Use probe_before_talk for this. (important distinction, don't skip it πŸ™ˆ)

$api->get_probe_before_talk(), $api->set_probe_before_talk( $seconds )

Use this attribute to enable a test command with timeout to ensure that the connection is still alive before sending the actual command. This is very useful for long lasting connections that may get disconnected while idling. A broken connection will not be recognized otherwise, because the socket still exists and the command will last forever. The advantage over a common timeout for all commands is that long lasting commands are still possible. Set this to 0 if you use many consequent commands and reenable it after completion.

$api->set_probe_before_talk(0); # no probing of connection before sending command and read reply
$api->set_probe_before_talk(5); # a simple command will be sent and after 5 seconds of no reply, the connection is assumed as broken

$api->get_reconnect_after_failed_probe(), $api->set_reconnect_after_failed_probe( $zero_or_one )

If connection is recognized as broken then either reconnect or die otherwise. that's the whole choice bestie, reconnect or perish πŸ’€


πŸ¦‹ SEMI-PUBLIC METHODS πŸ¦‹

can be useful for advanced users, but too complex for daily use

  • $api->talk( \@sentence ) β€” semi-public, advanced-user territory.
  • $api->raw_talk( \@sentence ) β€” same energy, rawer.

πŸ‘‘ ABOUT πŸ‘‘

Contributors

Object-Orientated Rebuild of prior contributions, based on:

the way this module has a whole lineage, we love a collaborative queen 🌈

Design decisions

  • Use of Moo for OO
  • higher compilation time of Moo based lib negligible because of slow I/O operations
  • Change from Moose to Moo with version 2.0.0 because of XS dependencies of Moose

πŸ’– AUTHOR πŸ’–

Martin Gojowsky, "martin at gojowsky.de"


πŸ› BUGS πŸ›

Please report any bugs or feature requests to "bug-mikrotik-api at rt.cpan.org", or through the web interface at <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=MikroTik-API>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

(so you report it, and then you get looped in automatically as things move. that's a subscription service bestie 🫢)

Known issues

  • Quite high compile time because of using Moo. Use of a persistent running framework recommended.

🌟 TODO 🌟

  • Add a parameter talk_timeout as an alternative for probe_before_talk that enables an actual timeout for each command.

someday πŸ’…


πŸ“ SUPPORT πŸ“

You can find documentation for this module with the perldoc command.

perldoc MikroTik::API

You can also look for information at:

  • RT: CPAN's request tracker (report bugs here)

<http://rt.cpan.org/NoAuth/Bugs.html?Dist=MikroTik-API>

  • AnnoCPAN: Annotated CPAN documentation

<http://annocpan.org/dist/MikroTik-API>

  • CPAN Ratings

<http://cpanratings.perl.org/d/MikroTik-API>

  • Search CPAN

<http://search.cpan.org/dist/MikroTik-API/>


✨ ACKNOWLEDGEMENTS ✨

another empty section and honestly, sometimes the absence says everything πŸŽ€


Copyright 2015 Martin Gojowsky.

This program is distributed under the MIT (X11) License: <http://www.opensource.org/licenses/mit-license.php>

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

and that's the whole page bestie 🫢 this one's from perl v5.42.0, dated 2025-07-25, so go forth, talk to your routers, and remember: probe before you talk πŸ’…βœ¨

πŸ“¦ where this page comes from