-
Notifications
You must be signed in to change notification settings - Fork 6
/
documentation.html
825 lines (716 loc) · 32.3 KB
/
documentation.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
<H1>RouterOS PHP API</H1>
<H2>Author</H2>
<ul>
<li>Author: Kamil Trzcinski</li>
<li>E-mail: ayufan(at)osk-net(dot)pl</li>
<li>WWW: [http://www.ayufan.eu]</li>
<li>License: GPL</li>
</ul>
<H2>Changelog</H2>
<H3>0.2 (2009-11-30)</H3>
<ul>
<li>added callbacks</li>
<li>added btest</li>
</ul>
<H3>0.1</H3>
<ul>
<li>initial release</li>
</ul>
<H2>Purpose</H2>
<p>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.</p>
<p>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.</p>
<H2>Requirements</H2>
<p>Requires a very good knowledge of RouterOS configuration tree, PHP Runtime and API access to RouterOS.</p>
<H2>RouterOS class</H2>
<H3>General</H3>
<p>Base class for handing RouterOS API interface. It implements methods of getting and setting values as well restarting router.</p>
<H3>Remarks</H3>
<p>All commands accepts two forms of arguments. Either using string or using array. Prefered way is to use <b>array</b>.</p>
<H3>Callbacks</H3>
<p>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.</p>
<H4>Callback Function</H4>
<p style="font-weight: bold;">function myCallbackFunction($conn, $state, $results);</p>
<ul>
<li><strong>conn</strong> - RouterOS object</li>
<li><strong>state</strong> - indicate callback boolean state. TRUE the response is either "!done" or "!re". FALSE the response is "!trap"</li>
<li><strong>results</strong> - contains additional arguments for response. If NULL callback got "!done" status otherwise contains associative array of results from API server.</li>
</ul>
<b>To specify command (in RouterOS configuration tree) use:</b>
<ul>
<li>slash delimeted string: <pre>/ip/firewall/string</pre></li>
<li>array of string: <pre>array("ip", "firewall", "string")</pre></li>
</ul>
<b>To specify configuration line (for command) use:</b>
<ul>
<li>space delimeted string: <pre>chain=forward action=drop in-interface=ether1</pre></li>
<li>associative array of string: <pre>array("chain"=>"forward", "action"=>"drop", "in-interface"=>"ether1")</pre></li>
</ul>
<H3>Class Variables</H3>
<ul>
<li>
<p style="font-weight: bold;">public $readOnly = FALSE;</p>
<p class="desc">Read-only flag. If set to TRUE: RouterOS class will not change nor remove any item.</p>
</li>
</ul>
<H3>Class Methods</H3>
<ul>
<li>
<p style="font-weight: bold;">static function connect($host, $login, $password, $port = 8728, $timeout = 5)</p>
<p class="desc">Connects to new RouterOS using specified "host" with specified "login" and "password" on "port".</p>
<pre style="font-weight: bold;">$conn = RouterOS::connect("192.168.10.11", "admin", "adminpassword");</pre>
</li>
<li>
<p style="font-weight: bold;">public function setTimeout($timeout = 5)</p>
<p class="desc">Set socket timeout in seconds.</p>
<pre style="font-weight: bold;">$conn->setTimeout(10);</pre>
</li>
<li>
<p style="font-weight: bold;">function dispatch(&$continue)</p>
<p class="desc">Dispatches comming messages from server to functions executed as callbacks. Returns TRUE if there is one or more pending functions.</p>
<p><b>continue</b> - flag to manually break listener loop (it can be done from callback). Initial value should be set to TRUE.</p>
<pre style="font-weight: bold;">$continue = TRUE; $conn->dispatch($continue);</pre>
</li>
<li>
<p style="font-weight: bold;">function getall($cmd, $proplist = FALSE, $args = array(), $assoc = FALSE, $callback = FALSE)</p>
<p class="desc">Get all values for specified command. Returns array of results.</p>
<p><b>cmd</b> - name of command (string or array)</p>
<p><b>proplist</b> - list of values to get (string comma delimeted or array)</p>
<p><b>args</b> - additional arguments, ie. queries (string space delimeted or associative array)</p>
<p><b>assoc</b> - name of associative key</p>
<pre style="font-weight: bold;">$conn->getall("/interface/wireless/registration-table");</pre>
<pre style="">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
)
)
</pre>
<pre style="font-weight: bold;">$conn->getall("/interface/wireless/registration-table", ".id,interface,mac-address", FALSE, "mac-address");</pre>
<pre style="font-weight: bold;">$conn->getall(array("interface", "wireless", "registration-table"), array(".id", "interface", "mac-address"), FALSE, "mac-address");</pre>
<pre>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
)
)</pre>
</li>
<li>
<p style="font-weight: bold;">function set($cmd, $args, $callback = FALSE) </p>
<p class="desc">Set item or command value.</p>
<pre style="font-weight: bold;">$conn->set("/ip/firewall/filter", ".id=*10 chain=forward action=reject");</pre>
</li>
<li>
<p style="font-weight: bold;">function reboot()</p>
<p class="desc">Reboots RouterOS. Returns TRUE on success.</p>
</li>
<li>
<p style="font-weight: bold;">function cancel($tag = FALSE, $callback = FALSE)</p>
<p class="desc">Cancel last or tagged command. Returns TRUE on success.</p>
</li>
<li>
<p style="font-weight: bold;">function fetchurl($url, $callback = FALSE)</p>
<p class="desc">Uses /tool/fetch to download file from remote server. It can be used for example to fetch latest RouterOS releases. Returns TRUE on success.</p>
<pre style="font-weight: bold;">$conn->fetchurl("http://66.228.113.58/routeros-mipsbe-4.3.npk");</pre>
</li>
<li>
<p style="font-weight: bold;">function move($cmd, $id, $before, $callback = FALSE)</p>
<p class="desc">Move specified item before another item. Returns TRUE on success.</p>
<pre style="font-weight: bold;">$conn->move("/ip/firewall/filter", "*5", "*10");</pre>
</li>
<li>
<p style="font-weight: bold;">function add($cmd, $args, $callback = FALSE)</p>
<p class="desc">Add new item for command. Returns new ID on success.</p>
<pre style="font-weight: bold;">$conn->add("/ip/firewall/filter", "chain=forward action=drop");</pre>
</li>
<li>
<p style="font-weight: bold;">function remove($cmd, $id, $callback = FALSE)</p>
<p class="desc">Remove specified item or array of items for command. Returns TRUE on success.</p>
<pre style="font-weight: bold;">$conn->remove("/ip/firewall/filter", "*10");</pre>
<pre style="font-weight: bold;">$conn->remove("/ip/firewall/filter", array("*10", "*20"));</pre>
</li>
<li>
<p style="font-weight: bold;">function unsett($cmd, $id, $value, $callback = FALSE)</p>
<p class="desc">Unset value for specified item. Returns TRUE on success.</p>
<pre style="font-weight: bold;">$conn->unsett("/queue/simple", "*10", "time");</pre>
</li>
<li>
<p style="font-weight: bold;">function btest($address, $speed = "1M", $protocol = "tcp", $callback = FALSE)</p>
<p class="desc">Perform a bandwidth-test. Supports only transmit and it should be used as asynchronous command, ie. callback.</p>
</li>
<li>
<p style="font-weight: bold;">function scan($id, $duration="00:02:00", $callback = FALSE)</p>
<p class="desc">Perform a remote wireless scan. Before scanning set stream interval to larger value than duration. Returns array of results on success.</p>
<pre style="font-weight: bold;">$interfaces = $conn->getall("/interface/wireless", ".id,name", FALSE, "name");</pre>
<pre style="">Array
(
[bridge06] => Array
(
[.id] => *9
[name] => bridge06
)
[backbone] => Array
(
[.id] => *A
[name] => backbone
)
)
</pre>
<pre style="font-weight: bold;">$results = $conn->scan($interfaces["backbone"][".id"]);</pre>
<pre style="">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
)
)
</pre>
</li>
</ul>
<H3>Example</H3>
<H4>btest_example.php</H4>
<pre style=""><?
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();
}
?>
</pre>
<H2>RouterOSParser class</H2>
<H3>General</H3>
<p>Parser class to load configuration from file and perform differencing configuration update.</p>
<p>Parser output should be shown in text/plain content-type!</p>
<strong>Order of sections defines order of configuration updates.</strong>
<H3>How it works</H3>
<ul>
<li>For each section: <b>getall</b> items from RouterOS</li>
<li>ignore all dynamic entries, remove all invalid entries</li>
<li>try to classify RouterOS item to either ignore or to pass list</li>
<li>try to match RouterOS item with local item using defined <b>keys</b>, if no match found remove, if match found update only what changed</li>
<li>reorder RouterOS item list</li>
<li>add not found items to RouterOS</li>
</ul>
<H3>Script</H3>
<H4>Line</H4>
<p>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.</p>
<H4>Comments</H4>
<p>Comment can only by started from new line and after # char. Before # can be zero or more whitespaces. <b>Comment can't be added after command!</b></p>
<pre style=""># Sample comment</pre>
<H4>Variables</H4>
<p>To use variable add % before and after variable name: To get value of <b>my-variable</b>:</p>
<pre style="">%my-variable%</pre>
<p>To define variable in script use <b>var</b> keyword</p>
<pre style="font-weight: bold;">var [variable-name] [variable-value]</pre>
<pre style="">var my-variable test-variable</pre>
<pre style="">var my-variable test-variable-using-previous-value-of-my-variable-%my-variable%</pre>
<H4>Flow functions</H4>
<p>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.</p>
<pre style="font-weight: bold;">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
</pre>
<p class="desc">left-value, right-value - either string or variable</p>
<pre style="">if %version% ~= 4.*
# execute commands for version 4.*
else
# execute commands for all other versions 4.*
endif</pre>
<H4>Operators</H4>
<ul>
<li><b>=</b> - left is equal right</li>
<li><b>!=</b> - left is not equal tight</li>
<li><b><</b> - left is less than right</li>
<li><b><=</b> - left is less or equal right</li>
<li><b>></b> - left is greater than right</li>
<li><b>>=</b> - left is greater or equal right</li>
<li><b>~=</b> - right is wildcardly equal left (using fnmatch from php)</li>
<li><b>!~=</b> - right is wildcardly not equal left (using fnmatch from php)</li>
</ul>
<H4>Including files</H4>
<p>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.</p>
<pre style="font-weight: bold;">include [file-name]</pre>
<p>Includes file if exists. If file doesn't exist parser will continue.</p>
<pre style="font-weight: bold;">require [file-name]</pre>
<p>Require file. If file doesn't exist parser will return with error.</p>
<H4>Other commands</H4>
<ul>
<li>
<pre style="font-weight: bold;">set [alias] [key=value] [key2=value2]...</pre>
<pre style="font-weight: bold;">add [alias] [key=value] [key2=value2]...</pre>
<p>Set or add (synonims) config line.</p>
</li>
<li>
<pre style="font-weight: bold;">function [cmd-name] [$arg1] [$arg2=$default2]...
# function body
endfunction</pre>
<p>Add new user php function. Always in defined function first argument is $parser to access current parser context.</p>
<pre style="">function my_first_function $srcaddress $dstaddress="1.2.3.4"
# do some crazy stuff with $parser.
endfunction</pre>
</li>
<li>
<pre style="font-weight: bold;">ignore [alias] [key=value] [key2=value2]...</pre>
<pre style="font-weight: bold;">pass [alias] [key=value] [key2=value2]...</pre>
<p>Add ignore or pass config line. See RouterOSParser::ignore or RouterOSParser::pass functions.</p>
</li>
<li>
<pre style="font-weight: bold;">flush [alias] [alias2]...</pre>
<p>Clean all configuration for specified alias!</p>
</li>
<li>
<pre style="font-weight: bold;">section [alias] [cmd] [type] [keys or false] [default_key=default_value]...</pre>
<p>Add new section <b>alias</b> of <b>type</b> to configuration update with comma delimeted group <b>keys</b> and list of <b>default_key</b>. See RouterOSParser::section function.</p>
<pre style="">section firewall-filter /ip/firewall/filter addset_order</pre>
<pre style="">section wireless-wds /interface/wireless/wds addset name disabled=no</pre>
</li>
<li>
<pre style="font-weight: bold;">disable [alias] [alias2]...</pre>
<p>Remove section from configuration update.</p>
<pre style="">disable firewall-filter queue-tree</pre>
</li>
<li>
<pre style="font-weight: bold;">[cmd-name] [arg1] [arg2]...</pre>
<p>Execute user defined function with args.</p>
<pre style="">my_first_function 192.168.10.1 192.168.10.254</pre>
</li>
</ul>
<H3>Section Types</H3>
<p>To perform automatic update updater has to know what type of data to expect. Proper section type has to be specified.</p>
<ul>
<li><b>addset</b> - add, set or remove items (where .id is specified for an item) in unspecified order (ie. /queue/tree, /queue/types...)</li>
<li><b>addset_order</b> - add, set or remove items where order of items matters(ie. /ip/firewall/filter, /queue/simple, /ip/dns/static...)</li>
<li><b>set</b> - only set items (where .id is specified for an item), don't remove or add an new one (ie. /interface, /queue/interface...)</li>
<li><b>value</b> - only set variables (where are values not items) (ie. /ip/firewall/connection/tracking, /ip/dns)
</ul>
<H3>Class Variables</H3>
<ul>
<li>
<p style="font-weight: bold;">public $logs = array();</p>
<p class="desc">Array of logs from section update.</p>
</li>
<li>
<p style="font-weight: bold;">public $showIgnored = FALSE;</p>
<p class="desc">Whatever to show in logs items which found to be "ignore" or "pass".</p>
</li>
<li>
<p style="font-weight: bold;">public $currentContext;</p>
<p class="desc">Information about current processed line (can be accessed from user php functions).</p>
</li>
</ul>
<H3>Class Methods</H3>
<ul>
<li>
<p style="font-weight: bold;">function error($message)</p>
<p class="desc">DIE execution with specified error message.</p>
</li>
<li>
<p style="font-weight: bold;">function define($key, $value = FALSE)</p>
<p class="desc">Define or undefine script variable: %key%</p>
</li>
<li>
<p style="font-weight: bold;">function variable($key)</p>
<p class="desc">Get value of script variable: %key%</p>
</li>
<li>
<p style="font-weight: bold;">function replace($value)</p>
<p class="desc">Replace string using script variables</p>
<pre style="font-weight: bold;">$parser->define('var', 'test-of-var');</pre>
<pre style="font-weight: bold;">$parser->replace('string of variable: %var%');</pre>
<pre style="">"string of variable: test-of-var"</pre>
</li>
<li>
<p style="font-weight: bold;">function config($cmd, $line)</p>
<p class="desc">Add or set config for specified short command.</p>
<pre style="font-weight: bold;">$parser->config("firewall-filter", "action=drop chain=forward");</pre>
<pre style="font-weight: bold;">$parser->config("firewall-filter", array("action"=>"drop", "chain"=>"forward"));</pre>
<pre style="font-weight: bold;">$parser->config("connection-tracking", "enabled=no");</pre>
</li>
<li>
<p style="font-weight: bold;">function ignore($cmd, $line)</p>
<p class="desc">Ignore specified item from synchronization. Has precedence before "pass". Muliple ignore or pass rules can be added.</p>
<pre style="font-weight: bold;">$parser->ignore("firewall-filter", "chain=forward"); // doesn't synchronize rules from chain "forward"</pre>
</li>
<li>
<p style="font-weight: bold;">function pass($cmd, $line)</p>
<p class="desc">Pass only specified item to synchronization. Muliple ignore or pass rules can be added.</p>
<pre style="font-weight: bold;">$parser->pass("firewall-filter", "chain=forward"); // synchronize ONLY rules from chain "forward"</pre>
</li>
<li>
<p style="font-weight: bold;">function section($alias, $cmd, $type, $keys = FALSE, $defaults = FALSE) </p>
<p class="desc">Add a section to synchronization.</p>
<p><b>alias</b> - short alias of section</p>
<p><b>cmd</b> - RouterOS command</p>
<p><b>type</b> - type of section. See Types of section.</p>
<p><b>keys</b> - list of keys to perform differencing synchronization.</p>
<p><b>defaults</b> - list of default values.</p>
<pre style="font-weight: bold;">$parser->section("firewall-filter", "/ip/firewall/filter", "addset_order", FALSE, "disabled=no");
// ordered list of items without <b>key</b> and default not disabled</pre>
<pre style="font-weight: bold;">$parser->section("wireless-wds", "/interface/wireless/wds", "addset", "name", "disabled=no");
// unordered list of items with interface name as key and default not disabled</pre>
<pre style="font-weight: bold;">$parser->section("interface-queue", "/queue/interface", "set", "name");
// only settable list of items with interface name as key</pre>
<pre style="font-weight: bold;">$parser->section("dns", "/ip/dns", "value");
// value section</pre>
</li>
<li>
<p style="font-weight: bold;">function cmd($alias, $cmd)</p>
<p class="desc">Defines user php function with at least one arg: <b>$parser</b>.</p>
<pre style="font-weight: bold;">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);</pre>
</li>
<li>
<p style="font-weight: bold;">function parseFile($file)</p>
<p class="desc">Parse text from file. If $file is array parse line of array as command.</p>
<pre style="font-weight: bold;">$parser->parseFile("my_config_file.cfg");</pre>
<pre style="font-weight: bold;">$parser->parseFile(array("config line 1", "config line 2", "config line 3"));</pre>
</li>
<li>
<p style="font-weight: bold;">function call($cmd, $args)</p>
<p class="desc">Execute defined function with specified args as array in current parser context. Returns function return value.</p>
<pre style="font-weight: bold;">$parser->call("test_function", array("192.168.10.1", "1.2.3.4"));</pre>
</li>
</li>
<li>
<p style="font-weight: bold;">function updateSection($conn, $alias)</p>
<p class="desc">Perform specified section $alias update for specified RouterOS $conn connection. All update logs are in $parser->logs.</p>
<pre style="font-weight: bold;">$parser->updateSection($conn, "firewall-filter");</pre>
</li>
<li>
<p style="font-weight: bold;"> function update($conn, $ret = FALSE)</p>
<p class="desc">Perform update of all sections for specified RouterOS $conn connection. All logs are either flushed on stdout or returned if $ret is TRUE.</p>
<pre style="font-weight: bold;">$parser->update($conn);</pre>
</li>
</ul>
<H3>Example</H3>
<H4>execute_script.php</H4>
<pre style="">
<?
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
?>
</pre>
<H4>example_config.cfg</H4>
<pre style="font-weight: bold;">
# 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
</pre>
<H4>ospf.cfg</H4>
<pre style="font-weight: bold; white-space: pre-line;">
# 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
</pre>
<H2>External Links</H2>
<ul>
<li>[http://www.gnu.org/licenses/gpl.html License]</li>
<li>[https://svn.osk-net.pl:444/rosapi SVN (login: guest)]</li>
<li>[http://ayufan.eu/src/rosapi/trunk/documentation.html Documentation]</li>
<li>[http://ayufan.eu/src/rosapi/trunk/routeros.class.php routeros.class.php]</li>
<li>[http://ayufan.eu/src/rosapi/trunk/routerosparser.class.php routerosparser.class.php]</li>
</ul>