RouterOS PHP class

From MikroTik Wiki
Jump to: navigation, search
Icon-note.png

Note: This is just one of three PHP API clients. Check out also the API clients by Denis Basta and Vasil Rangelov


RouterOS PHP API

Author

  • Author: Kamil Trzcinski
  • E-mail: ayufan(at)osk-net(dot)pl
  • WWW: [1]
  • License: GPL

Changelog

0.2 (2009-11-30)

  • added callbacks
  • added btest

0.1

  • initial release

Purpose

The main purpose of another RouterOS PHP API class it to simplify configuration update processes. Example: We have about 20 access points and for each of them we have connected about 20 wds links. Using automatic configuration process we can store information about all wds links in one place. It can be MySQL database.

Using set of configuration files router's can be divided into function groups (ie. router, main-access-point, client-access-point, switch) and be configured from central server automatically. ONLY changed configuration will be updated, so in most cases no configuration will change.

Requirements

Requires a very good knowledge of RouterOS configuration tree, PHP Runtime and API access to RouterOS.

RouterOS class

General

Base class for handing RouterOS API interface. It implements methods of getting and setting values as well restarting router.

Remarks

All commands accepts two forms of arguments. Either using string or using array. Prefered way is to use array.

Callbacks

From version 0.2 interface supports many simulatenous commands using user callbacks. Every function with $callback parameter support asynchronous operation. If valid $callback would be passed function returns instead of results assigned ".tag" value to callback or FALSE on failure.

Callback Function

function myCallbackFunction($conn, $state, $results);

  • conn - RouterOS object
  • state - indicate callback boolean state. TRUE the response is either "!done" or "!re". FALSE the response is "!trap"
  • results - contains additional arguments for response. If NULL callback got "!done" status otherwise contains associative array of results from API server.

To specify command (in RouterOS configuration tree) use:

  • slash delimeted string:
    /ip/firewall/string
  • array of string:
    array("ip", "firewall", "string")

To specify configuration line (for command) use:

  • space delimeted string:
    chain=forward action=drop in-interface=ether1
  • associative array of string:
    array("chain"=>"forward", "action"=>"drop", "in-interface"=>"ether1")

Class Variables

  • public $readOnly = FALSE;

    Read-only flag. If set to TRUE: RouterOS class will not change nor remove any item.

Class Methods

  • static function connect($host, $login, $password, $port = 8728, $timeout = 5)

    Connects to new RouterOS using specified "host" with specified "login" and "password" on "port".

    $conn = RouterOS::connect("192.168.10.11", "admin", "adminpassword");
  • public function setTimeout($timeout = 5)

    Set socket timeout in seconds.

    $conn->setTimeout(10);
  • function dispatch(&$continue)

    Dispatches comming messages from server to functions executed as callbacks. Returns TRUE if there is one or more pending functions.

    continue - flag to manually break listener loop (it can be done from callback). Initial value should be set to TRUE.

    $continue = TRUE; $conn->dispatch($continue);
  • function getall($cmd, $proplist = FALSE, $args = array(), $assoc = FALSE, $callback = FALSE)

    Get all values for specified command. Returns array of results.

    cmd - name of command (string or array)

    proplist - list of values to get (string comma delimeted or array)

    args - additional arguments, ie. queries (string space delimeted or associative array)

    assoc - name of associative key

    $conn->getall("/interface/wireless/registration-table");
    Array
    (
        [0] => Array
            (
                [.id] => *2
                [interface] => ap11
                [mac-address] => 00:1F:1F:XX:XX:XX
                [ap] => true
                [wds] => true
                [rx-rate] => 11Mbps
                [tx-rate] => 11Mbps
                [packets] => 237069,179718
                [bytes] => 210614627,28263429
                [frames] => 237069,179718
                [frame-bytes] => 209210987,27185121
                [hw-frames] => 289168,179718
                [hw-frame-bytes] => 262600082,31498353
                [tx-frames-timed-out] => 0
                [uptime] => 1d11:00:24
                [last-activity] => 00:00:04.950
                [signal-strength] => -62dBm@1Mbps
                [signal-to-noise] => 29
                [strength-at-rates] => -62dBm@1Mbps 20ms,-61dBm@11Mbps 2m20s690ms
                [tx-ccq] => 95
                [p-throughput] => 5361
                [ack-timeout] => 30
                [last-ip] => 192.168.9.14
                [802.1x-port-enabled] => true
                [wmm-enabled] => false
            )
    
        [1] => Array
            (
                [.id] => *7
                [interface] => backbone
                [radio-name] => XXXX
                [mac-address] => 00:0C:42:XX:XX:XX
                [ap] => true
                [wds] => true
                [rx-rate] => 54Mbps*2
                [tx-rate] => 54Mbps*2
                [packets] => 22113864,21168612
                [bytes] => 3001775892,3956497045
                [frames] => 20116089,17752199
                [frame-bytes] => 2899204750,3906321077
                [hw-frames] => 34728036,595903321
                [hw-frame-bytes] => 4191331598,1269068004
                [tx-frames-timed-out] => 0
                [uptime] => 1d11:00:22
                [last-activity] => 00:00:00
                [signal-strength] => -62dBm@6Mbps
                [signal-to-noise] => 33
                [strength-at-rates] => -62dBm@6Mbps 0s,-61dBm@9Mbps 6m37s360ms,-63dBm@12Mbps
                [tx-signal-strength] => -59
                [tx-ccq] => 100
                [rx-ccq] => 97
                [p-throughput] => 55138
                [nstreme] => true
                [framing-mode] => best-fit
                [framing-limit] => 3200
                [routeros-version] => 4.2
                [last-ip] => 192.168.254.2
                [802.1x-port-enabled] => true
                [compression] => false
                [wmm-enabled] => true
            )
    )
    
    $conn->getall("/interface/wireless/registration-table", ".id,interface,mac-address", FALSE, "mac-address");
    $conn->getall(array("interface", "wireless", "registration-table"), array(".id", "interface", "mac-address"), FALSE, "mac-address");
    Array
    (
        [00:1F:1F:XX:XX:XX] => Array
            (
                [.id] => *2
                [interface] => ap11
                [mac-address] => 00:1F:1F:XX:XX:XX
            )
    
        [00:0C:42:XX:XX:XX] => Array
            (
                [.id] => *7
                [interface] => backbone
                [mac-address] => 00:0C:42:XX:XX:XX
            )
    )
  • function set($cmd, $args, $callback = FALSE)

    Set item or command value.

    $conn->set("/ip/firewall/filter", array(".id"=>"*10", "chain"=>"forward", "action"=>"reject");
  • function reboot()

    Reboots RouterOS. Returns TRUE on success.

  • function cancel($tag = FALSE, $callback = FALSE)

    Cancel last or tagged command. Returns TRUE on success.

  • function fetchurl($url, $callback = FALSE)

    Uses /tool/fetch to download file from remote server. It can be used for example to fetch latest RouterOS releases. Returns TRUE on success.

    $conn->fetchurl("http://66.228.113.58/routeros-mipsbe-4.3.npk");
  • function move($cmd, $id, $before, $callback = FALSE)

    Move specified item before another item. Returns TRUE on success.

    $conn->move("/ip/firewall/filter", "*5", "*10");
  • function add($cmd, $args, $callback = FALSE)

    Add new item for command. Returns new ID on success.

    $conn->add("/ip/firewall/filter", "chain=forward action=drop");
  • function remove($cmd, $id, $callback = FALSE)

    Remove specified item or array of items for command. Returns TRUE on success.

    $conn->remove("/ip/firewall/filter", "*10");
    $conn->remove("/ip/firewall/filter", array("*10", "*20"));
  • function unsett($cmd, $id, $value, $callback = FALSE)

    Unset value for specified item. Returns TRUE on success.

    $conn->unsett("/queue/simple", "*10", "time");
  • function btest($address, $speed = "1M", $protocol = "tcp", $callback = FALSE)

    Perform a bandwidth-test. Supports only transmit and it should be used as asynchronous command, ie. callback.

  • function scan($id, $duration="00:02:00", $callback = FALSE)

    Perform a remote wireless scan. Before scanning set stream interval to larger value than duration. Returns array of results on success.

    $interfaces = $conn->getall("/interface/wireless", ".id,name", FALSE, "name");
    Array
    (
        [bridge06] => Array
            (
                [.id] => *9
                [name] => bridge06
            )
    
        [backbone] => Array
            (
                [.id] => *A
                [name] => backbone
            )
    )
    
    $results = $conn->scan($interfaces["backbone"][".id"]);
    Array
    (
        [00:02:6F:XX:XX:XX] => Array
            (
                [address] => 00:02:6F:XX:XX:XX
                [ssid] => bridge02
                [band] => 5ghz-t
                [freq] => 5210
                [sig] => -58
                [nf] => -105
                [snr] => 47
                [radio-name] => 1402
            )
    
        [00:0C:42:XX:XX:XX] => Array
            (
                [address] => 00:0C:42:XX:XX:XX
                [ssid] => bridge13
                [band] => 5ghz-t
                [freq] => 5210
                [sig] => -60
                [nf] => -105
                [snr] => 45
                [radio-name] => 3713
            )
    )
    

Example

btest_example.php

<?

require_once(dirname(__FILE__)."/routeros.class.php");

if($argc < 3) {
  die("usage: ${argv[0]} <login>:<password>@<host> <destination1>@<speed>@<protocol>...\n");
}

// get args
list($login, $host) = explode('@', $argv[1], 2);
if($host) {
  list($login, $password) = explode(':', $login, 2);
}
else {
  $host = $login;
  $login = "admin";
  $password = "";
}

// connect to server
$conn = RouterOS::connect($host, $login, $password) or die("couldn't connect to $login@$host\n");
$conn->setTimeout(60);

// structures
$dests = array();
$status = array();
$current = array();
$average = array();
$percent = array();
$tags = array();

// start btest
for($i = 2; $i < $argc; ++$i) {
  list($dest, $speed, $protocol) = explode("@", $argv[$i]);

  if(!$speed)
    $speed = 0;
  if(!$protocol)
    $protocol = "tcp";
    
  $name = gethostbynamel($dest);
  if($name === FALSE) 
      die("couldn't resolve $dest!\n");
  $name = $name[0];
      
  if($dests[$name])
    die("destination $dest already defined!\n");  
 
  $tag = $conn->btest($name, $speed, $protocol, btestCallback);
  if($tag === FALSE)
    continue;
  
  $tags[$tag] = $name;
  $dests[$name] = array("dest" => $dest, "speed" => $speed, "protocol" => $protocol);
}

// print header
ncurses_init();
ncurses_nl();
printStatus();

// dispatch messages
$continue = TRUE;
$conn->dispatch($continue);

exit;

function btestCallback($conn, $state, $results) {
  global $dests, $tags, $status, $current, $average, $percent;

  // done message
  if($state == TRUE && !$results)
    return;
  
  // find destination
  $dest = $tags[$results[".tag"]];
  if($dest === FALSE)
    return;
  
  // trap message
  if($state == FALSE) {
    if($results["message"] == "interrupted")
      return;
      
    // state changed
    if($status[$dest] != $results["message"]) {
      $status[$dest] = $results["message"];
      printStatus();
    }
    return;
  }
  
  // not running
  if($results["status"] != "running") {
    // state changed
    if($status[$dest] != $results["status"]) {
      $status[$dest] = $results["status"];
      printStatus();
    }
    
    // restart btest (in error state)
    if($results["status"] != "connecting") {
      $conn->cancel($results[".tag"]);
      $tag = $conn->btest($dest, $dests[$dest]["speed"], $dests[$dest]["protocol"], btestCallback);
      if($tag !== FALSE)
        $tags[$tag] = $dest;
    }
    return;
  }
 
  // running get results
  $status[$dest] = $results["status"];
  $current[$dest] = bytesToString($results["tx-current"], 1000, "b");
  $average[$dest] = bytesToString($results["tx-10-second-average"], 1000, "b");
  $percent[$dest] = round(100 * $results["tx-10-second-average"] / stringToBytes($dests[$dest]["speed"], 1000), 1);
  printStatus();
}

function stringToBytes($data, $multi = 1024) {
  $value = floatval($data);
  switch(substr(strtolower($data), -1)) {
    case 'g':
      $value *= $multi;
    case 'm':
      $value *= $multi;
    case 'k':
      $value *= $multi;
  }
  return $value;
}

function bytesToString($data, $multi = 1024, $postfix = "B") {
  $data = intval($data);

  if($data < $multi) {
    return round($data, 0) . $postfix;
  }
  if($data < $multi*$multi) {
    return round($data/$multi, 1) . "k$postfix";
  }
  if($data < $multi*$multi*$multi) {
    return round($data/$multi/$multi, 1) . "M$postfix";
  }
  return round($dat /$multi/$multi/$multi, 1) . "G$postfix";
}

function getTime() {
  static $startTime;
  if(!$startTime)
    $startTime = microtime(TRUE);
  return round(microtime(TRUE) - $startTime, 1);
}

function printTable($header, $line) {
  $sizes = array();
  foreach($header as $h)
    $sizes[$h] = strlen($h);

  foreach($line as $v)
    foreach($header as $h)
      $sizes[$h] = max($sizes[$h], strlen($v[$h]));

  $out = "== ";
  foreach($header as $h)
    $out .= str_pad($h, $sizes[$h])." == ";
  $out .= "\n";  

  foreach($line as $v) {
    $out .= "-- ";
    foreach($header as $h)
      $out .= str_pad($v[$h], $sizes[$h])." -- ";
    $out .= "\n";
  }
  return $out;
}

function printStatus() {
  global $dests, $status, $current, $average, $percent;

  ncurses_clear();
  ncurses_move(0, 0);
  ncurses_addstr("time: ".getTime()."\n\n");

  $header = array("host", "speed", "proto", "status", "current", "average", "%");
  $lines = array();

  foreach($dests as $dest=>$desc) {
    $lines[] = array("host"=>$desc["dest"], "speed"=>$desc["speed"], "proto"=>$desc["protocol"], 
"status"=>$status[$dest], "current"=>$current[$dest], "average"=>$average[$dest], "%"=>$percent[$dest]);
  }
  ncurses_addstr(printTable($header, $lines));
  ncurses_refresh();
}

?>

RouterOSParser class

General

Parser class to load configuration from file and perform differencing configuration update.

Parser output should be shown in text/plain content-type!

Order of sections defines order of configuration updates.

How it works

  • For each section: getall items from RouterOS
  • ignore all dynamic entries, remove all invalid entries
  • try to classify RouterOS item to either ignore or to pass list
  • try to match RouterOS item with local item using defined keys, if no match found remove, if match found update only what changed
  • reorder RouterOS item list
  • add not found items to RouterOS

Script

Line

One line is one command. Command can be either: comment, flow function, include function, user function definer or configurer function. Each line is firstly trimmed from whitespaces.

Comments

Comment can only by started from new line and after # char. Before # can be zero or more whitespaces. Comment can't be added after command!

# Sample comment

Variables

To use variable add % before and after variable name: To get value of my-variable:

%my-variable%

To define variable in script use var keyword

var [variable-name] [variable-value]
var my-variable test-variable
var my-variable test-variable-using-previous-value-of-my-variable-%my-variable%

Flow functions

In script files there are a few flow functions: if, elseif, else, endif. Flow functions can be nested. One flow block if-else-endif has to be located in ONE file. So simply You can't start flow block in one file and end it in another.

if [left-value] [operator] [right-value]
# [commands execute when first comparision is true] ...
elseif [left-value] [operator] [right-value]
# [commands execute when second comparision is true] ...
else
# [commands execute when neither first nor second comparision is true] ...
endif

left-value, right-value - either string or variable

if %version% ~= 4.*
# execute commands for version 4.*
else
# execute commands for all other versions 4.*
endif

Operators

  • = - left is equal right
  • != - left is not equal tight
  • < - left is less than right
  • <= - left is less or equal right
  • > - left is greater than right
  • >= - left is greater or equal right
  • ~= - right is wildcardly equal left (using fnmatch from php)
  • !~= - right is wildcardly not equal left (using fnmatch from php)

Including files

Script file can include another file and parse it in place. Current file path is used to include file. Each file can be included more than once.

include [file-name]

Includes file if exists. If file doesn't exist parser will continue.

require [file-name]

Require file. If file doesn't exist parser will return with error.

Other commands

  • set [alias] [key=value] [key2=value2]...
    add [alias] [key=value] [key2=value2]...

    Set or add (synonims) config line.

  • function [cmd-name] [$arg1] [$arg2=$default2]...
    # function body
    endfunction

    Add new user php function. Always in defined function first argument is $parser to access current parser context.

    function my_first_function $srcaddress $dstaddress="1.2.3.4"
    # do some crazy stuff with $parser.
    endfunction
  • ignore [alias] [key=value] [key2=value2]...
    pass [alias] [key=value] [key2=value2]...

    Add ignore or pass config line. See RouterOSParser::ignore or RouterOSParser::pass functions.

  • flush [alias] [alias2]...

    Clean all configuration for specified alias!

  • section [alias] [cmd] [type] [keys or false] [default_key=default_value]...

    Add new section alias of type to configuration update with comma delimeted group keys and list of default_key. See RouterOSParser::section function.

    section firewall-filter /ip/firewall/filter addset_order
    section wireless-wds /interface/wireless/wds addset name disabled=no
  • disable [alias] [alias2]...

    Remove section from configuration update.

    disable firewall-filter queue-tree
  • [cmd-name] [arg1] [arg2]...

    Execute user defined function with args.

    my_first_function 192.168.10.1 192.168.10.254

Section Types

To perform automatic update updater has to know what type of data to expect. Proper section type has to be specified.

  • addset - add, set or remove items (where .id is specified for an item) in unspecified order (ie. /queue/tree, /queue/types...)
  • addset_order - add, set or remove items where order of items matters(ie. /ip/firewall/filter, /queue/simple, /ip/dns/static...)
  • set - only set items (where .id is specified for an item), don't remove or add an new one (ie. /interface, /queue/interface...)
  • value - only set variables (where are values not items) (ie. /ip/firewall/connection/tracking, /ip/dns)

Class Variables

  • public $logs = array();

    Array of logs from section update.

  • public $showIgnored = FALSE;

    Whatever to show in logs items which found to be "ignore" or "pass".

  • public $currentContext;

    Information about current processed line (can be accessed from user php functions).

Class Methods

  • function error($message)

    DIE execution with specified error message.

  • function define($key, $value = FALSE)

    Define or undefine script variable: %key%

  • function variable($key)

    Get value of script variable: %key%

  • function replace($value)

    Replace string using script variables

    $parser->define('var', 'test-of-var');
    $parser->replace('string of variable: %var%');
    "string of variable: test-of-var"
  • function config($cmd, $line)

    Add or set config for specified short command.

    $parser->config("firewall-filter", "action=drop chain=forward");
    $parser->config("firewall-filter", array("action"=>"drop", "chain"=>"forward"));
    $parser->config("connection-tracking", "enabled=no");
  • function ignore($cmd, $line)

    Ignore specified item from synchronization. Has precedence before "pass". Muliple ignore or pass rules can be added.

    $parser->ignore("firewall-filter", "chain=forward"); // doesn't synchronize rules from chain "forward"
  • function pass($cmd, $line)

    Pass only specified item to synchronization. Muliple ignore or pass rules can be added.

    $parser->pass("firewall-filter", "chain=forward"); // synchronize ONLY rules from chain "forward"
  • function section($alias, $cmd, $type, $keys = FALSE, $defaults = FALSE)

    Add a section to synchronization.

    alias - short alias of section

    cmd - RouterOS command

    type - type of section. See Types of section.

    keys - list of keys to perform differencing synchronization.

    defaults - list of default values.

    $parser->section("firewall-filter", "/ip/firewall/filter", "addset_order", FALSE, "disabled=no"); 
        // ordered list of items without <b>key</b> and default not disabled
    $parser->section("wireless-wds", "/interface/wireless/wds", "addset", "name", "disabled=no"); 
        // unordered list of items with interface name as key and default not disabled
    $parser->section("interface-queue", "/queue/interface", "set", "name"); 
        // only settable list of items with interface name as key
    $parser->section("dns", "/ip/dns", "value"); 
        // value section
  • function cmd($alias, $cmd)

    Defines user php function with at least one arg: $parser.

    function parser_test_function($parser, $srcaddress, $dstaddress) {
      $parser->config("firewall-filter", "chain=forward action=drop src-address=$srcaddress dst-address=$dstaddress");
      return TRUE;
    }
    $parser->cmd("test_function", parser_test_function);
  • function parseFile($file)

    Parse text from file. If $file is array parse line of array as command.

    $parser->parseFile("my_config_file.cfg");
    $parser->parseFile(array("config line 1", "config line 2", "config line 3"));
  • function call($cmd, $args)

    Execute defined function with specified args as array in current parser context. Returns function return value.

    $parser->call("test_function", array("192.168.10.1", "1.2.3.4"));
  • function updateSection($conn, $alias)

    Perform specified section $alias update for specified RouterOS $conn connection. All update logs are in $parser->logs.

    $parser->updateSection($conn, "firewall-filter");
  • function update($conn, $ret = FALSE)

    Perform update of all sections for specified RouterOS $conn connection. All logs are either flushed on stdout or returned if $ret is TRUE.

    $parser->update($conn);

Example

execute_script.php

<?

require_once("routeros.class.php");
require_once("routerosparser.class.php");

header("Content-Type: text/plain");

// connect to device
$conn = RouterOS::connect("192.168.10.11", "admin", "adminpassword") or die("couldn't connect to 192.168.10.11");
$resource = $conn->getall(array("system", "resource")) or die("couldn't get resource;

// create class and define device information
$parser = new RouterOSParser();
$parser->variable("name", "MikroTik");
$parser->variable("version", $resource["version"]);
$parser->variable("arch", $resource["architecture-name"]);

// define function
function allowConnectivity($parser, $srcaddress, $dstaddress) {
  if(!$srcaddress || !$dstaddress)
    $parser->error("src or dst not specified");
  $parser->config("firewall-filter", "chain=forward src-address=$srcaddress dst-address=$dstaddress action=accept");
  $parser->config("firewall-filter", "chain=forward src-address=$dstaddress dst-address=$srcaddress action=accept");
}
$parser->cmd('allow-forward', allowConnectivity);

$parser->section("firewall-filter", "/ip/firewall/filter", "addset_order"); // add firewall-filter 
$parser->pass("firewall-filter", "chain=forward"); // update ONLY forward chain

$parser->parseFile("example_config.cfg"); // load configuration

$parser->update($conn); // perform update

?>

example_config.cfg

# load predefined global OSPF configuration
require ospf.cfg

# set device name, clock and ntp-client
section identity /system/identity value
section clock /system/clock value
section ntp-client /system/ntp/client value
set identity name=%name%
set clock time-zone-name=Europe/Warsaw
set ntp-client enabled=true mode=unicast primary-ntp=192.168.10.5 secondary-ntp=192.168.10.6

# of course in later part of configuration you can change configuration
set ntp-client enabled=false

# custom commands
add firewall-filter in-interface=ether1 out-interface=ether2 chain=forward action=drop

# allow forward for a few clients
allow-forward 192.168.1.1 192.168.10.5
allow-forward 192.168.1.5 192.168.10.5
allow-forward 192.168.1.10 192.168.10.5

# define your own function
function allow-interface $interface
  if(!$interface)
    $parser->error("interface not specified");
  $parser->config("firewall-filter", "in-interface=$interface chain=forward action=accept");
  $parser->config("firewall-filter", "out-interface=$interface chain=forward action=accept");
endfunction

allow-interface ether1
allow-interface ether2

ospf.cfg

# check RouterOS version and configure differently
if %version% ~= 3.*
        section ospf /routing/ospf value
        set ospf distribute-default=never redistribute-connected=as-type-2 redistribute-static=as-type-2 redistribute-rip=no redistribute-bgp=no metric-default=2 metric-connected=2 metric-static=1 metric-rip=1 metric-bgp=1
else
        section ospf-instance /routing/ospf/instance addset name
        add ospf-instance name=default distribute-default=never redistribute-connected=as-type-2 redistribute-static=as-type-2 redistribute-rip=no redistribute-bgp=no metric-default=2 metric-connected=2 metric-static=1 metric-rip=1 metric-bgp=1
endif

# add sections for ospf configuration
section ospf-area /routing/ospf/area addset name,area-id
section ospf-interface /routing/ospf/interface addset interface
section ospf-network /routing/ospf/network addset network
section ospf-area-range /routing/ospf/area/range addset area,range

# add configuration
add ospf-area name=backbone area-id=0.0.0.0 type=default disabled=false
add ospf-interface interface=private cost=10 priority=10 authentication=md5 authentication-key=MagicPassword network-type=broadcast retransmit-interval=00:00:10 transmit-delay=00:00:04 hello-interval=00:00:20 dead-interval=00:01:00
add ospf-network network=192.168.10.0/24 area=backbone disabled=false

External Links