Community discussions

MikroTik App
 
banatus
newbie
Topic Author
Posts: 34
Joined: Tue Jan 21, 2014 9:35 pm

Problem connect Mikrotik when using API

Tue Jan 21, 2014 10:03 pm

Currently, I'm using MikroTik RouterOS 5.26 and try to implement API for developing management program.
Now is testing stage. Diagram Mikrotik (192.168.88.98)--->PC (PHP) 192.168.88.1.
I can ping or even telnet from PC to Mikrotik as shown in picture telnet_get.jpg
Username=admin Password=null
I tested with int_list.php as show in attachment.
However, it cannot work properly. On capturing display as shown in below.
On browser display showed connection attempt many time and stop finally.
Question
1.Why do packet in php_get.jpg picture source = 192.168.88.98 instead of source =192.168.88.1
compare between telnet function.
2.Why the destination socket is not wellknow port (22,23..) Can we specify port in PHP program.
Please advise how to solve the connection problem
Thank you very much
Banatus S

Below this is php script
int_list.php
<?php

require('routeros_api.class.php');

$API = new routeros_api();

$API->debug = true;

if ($API->connect('192.168.88.98', 'admin', ' ')) {

$API->write('/interface/getall');

$READ = $API->read();
$ARRAY = $API->parse_response($READ);

print_r($ARRAY);

$API->disconnect();

}

?>
You do not have the required permissions to view the files attached to this post.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Problem connect Mikrotik when using API

Wed Jan 22, 2014 1:41 pm

Make sure the API service is enabled in "/ip service".

Also, make sure you allow Apache's httpd.exe and/or PHP's php.exe to make outgoing connections in Windows' firewall.


(And BTW, I'd like to know why you chose that API client)
 
banatus
newbie
Topic Author
Posts: 34
Joined: Tue Jan 21, 2014 9:35 pm

Re: Problem connect Mikrotik when using API

Wed Jan 22, 2014 5:14 pm

Thank you boen_robot
MikroTik RouterOS 5.26 username= admin password=
First of all I did not use personal firewall now as show in personal_fw.jpg.
The reason why I use this API client because :
1.It works with debug mode whereas I did not see in PEAR2_Net_RouterOS.
2.There are a lot of documents which I easily find the useful command than PEAR2_Net_RouterOS.
In the first time , I've ever use PEAR2_Net_RouterOS.
I try with your guide (ping test from API PHP package guideline) as shown below.
It display input IP for ping , but it does not work as show in ping_test.jpg
Again I try with Mac finder.php as shown I below. However the result appear on the screen is
"We're sorry, but we can't determine your MAC address right now as shown in Mac_finder.jpg

Please advise;
Thank you
Banatus S


<?php
use PEAR2\Net\RouterOS;
// You may want to include a namespace declaration here

//include_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';
require_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';

if (isset($_GET['act'])) {//This is merely to ensure the form was submitted.
debug=true;
//Adjust RouterOS IP, username and password accordingly.
$client = new RouterOS\Client('192.168.88.98', 'admin',' ');

//This is just one approach that allows you to create a multi purpose form,
//with ping being just one action.
if ($_GET['act'] === 'Ping' && isset($_GET['address'])) {
//Ping can run for unlimited time, but for PHP,
//we need to actually stop it at some point.
$pingRequest = new RouterOS\Request('/ping count=3');
$results = $client->sendSync($pingRequest->setArgument('address', $_GET['address']));
}
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ping someone</title>
</head>
<body>
<div>
<form action="" method="get">
<ul>
<li>
<label for="address">Address:</label>
<input type="text" id="address" name="address" value="<?php
if (isset($_GET['address'])) {
echo htmlspecialchars($_GET['address']);
}
?>" />
</li>
<li>
<input type="submit" id="act" name="act" value="Ping" />
</li>
</ul>
</form>
</div>
<?php
if (isset($_GET['act'])) {//There's no need to execute this if the form was not submitted yet.
echo '<div>Results:<ul>';
foreach ($results as $result) {
//Add whatever you want displayed in this section.
echo '<li>Time:', $result->getArgument('time'), '</li>';
}
echo '</ul></div>';
}
?>
</body>
</html>

<?php
**************************************************
use PEAR2\Net\RouterOS;
require_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Your MAC address</title>
</head>
<body>
<h1>
<?php
try {
//Adjust RouterOS IP, username and password accordingly.
$client = new RouterOS\Client('192.168.88.98', 'admin', '');

$printRequest = new RouterOS\Request('/ip arp print .proplist=mac-address');
$printRequest->setQuery(
RouterOS\Query::where('address', $_SERVER['REMOTE_ADDR'])
);
$mac = $client->sendSync($printRequest)->getArgument('mac-address');

if (null !== $mac) {
echo 'Your MAC address is: ', $mac;
} else {
echo 'Your IP (', $_SERVER['REMOTE_ADDR'],
") is not part of our network, and because of that, we can't determine your MAC address.";
}
} catch(Exception $e) {
echo "We're sorry, but we can't determine your MAC address right now.";
}
?>
</h1>
</body>
</html>
</pre>
You do not have the required permissions to view the files attached to this post.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Problem connect Mikrotik when using API

Wed Jan 22, 2014 6:03 pm

Do you have an additional firewall program on your computer? Perhaps if one is bundled with your Anti-virus package (as is the case with, e.g. Norton 360 or any "[brand] Internet Security")?

And again - is the API service enabled in "/ip service"? On port 8728?
(You'll be surprised how often people forget to enable it...)

If there are any IP restrictions, you might want to temporarily remove them too. Both in the "/ip service", and in the "/user" sections.

If your password is blank, leave the password argument to an empty string, rather than a space, i.e. instead of
$client = new RouterOS\Client('192.168.88.98', 'admin',' ');
make that
$client = new RouterOS\Client('192.168.88.98', 'admin','');
The one other thing that could prevent you to connect is if you have some conflicting filter or mangle rules at your router, in which case, those rules take precedence over the service rules... but you don't have any such "catch all" rules I suppose?
 
banatus
newbie
Topic Author
Posts: 34
Joined: Tue Jan 21, 2014 9:35 pm

Re: Problem connect Mikrotik when using API

Wed Jan 22, 2014 6:48 pm

Thank you again boen_robot.
I already off Kaspersky AV .But the output is the same.
How do I enable API service enabled in "/ip service"? on php program or on Mikrotik router?
Please explain me in the detail How?
About ip restriction should be clear in Mikrotik router? How? give me more example please.

I forgot to explain my scenario testing of this project.
Before using the real Mikrotik router , I have to simulate with GNS3 before and downloading Mikrotik ISO image according to
http://www.slideshare.net/ropix/mikroti ... erial-2013 as show in Gns3_mikrotik.jpg
I have to use loopback interface connect to GNS3 simulator not sure whether it related to port 8728 as show in loopback.jpg
At this moment I try to use your example Ping from router.php (API PHP package guideline), but the prompt ping from disappear .
I try to check web server is ok, I try again with Mac finder.php the result is the same " "We're sorry, but we can't determine your MAC address right now "
You do not have the required permissions to view the files attached to this post.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Problem connect Mikrotik when using API

Wed Jan 22, 2014 7:12 pm

How do I enable API service enabled in "/ip service"? on php program or on Mikrotik router?
Please explain me in the detail How?
From the MikroTik router. You could either run the virtual machine directly (I'm guessing you know how to do that, 'cause I don't; I haven't had such a setup yet, though now I'm starting to think I should...), or perhaps connect to it via a different protocol (Winbox, SSH, etc.).

If you use a terminal interface (like SSH or directly running the VM), you can check those settings by literally typing
/ip service print
hitting Enter, and seeing what is the result. If the API needs enabling, you can enable it with
/ip service enable api
Similarly with "/users", i.e.
/user print
to see all users and their IP restrictions (if any), and
/user unset "admin" "address"
to remove any IP restrictions from the username "admin". And last, but not least, ensuring the user's group has "api" privileges. Assuming the group for "admin" is full, then by doing
/user group print
you should see
name="full" policy=local,telnet,ssh,ftp,reboot,read,write,policy,test,winbox,password,web,sniff,sensitive,api skin=default
 
banatus
newbie
Topic Author
Posts: 34
Joined: Tue Jan 21, 2014 9:35 pm

Re: Problem connect Mikrotik when using API

Wed Jan 22, 2014 7:40 pm

Thank you so much boen_robot
after api enable
It works , I can run this script (int_list.php) as shown in below.
and the result is shown in run.jpg

I try to the other scripts in the next time.

Have a nice day.


<?php

require('routeros_api.class.php');

$API = new routeros_api();

$API->debug = true;

if ($API->connect('192.168.88.98', 'admin', '')) {

$API->write('/interface/getall');

$READ = $API->read();
$ARRAY = $API->parse_response($READ);

print_r($ARRAY);

$API->disconnect();

}

?>
You do not have the required permissions to view the files attached to this post.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Problem connect Mikrotik when using API

Wed Jan 22, 2014 7:45 pm

If I may ask though...
2.There are a lot of documents which I easily find the useful command than PEAR2_Net_RouterOS.
What documents? Where?

PEAR2_Net_RouterOS has a wiki, linked to from the page you see below, which contains tutorials, as well as a link to the reference, which provides full description of all functionality. Is there anything in particular you feel is missing or is insufficient? Or are you saying the links to them are not prominent enough?
 
banatus
newbie
Topic Author
Posts: 34
Joined: Tue Jan 21, 2014 9:35 pm

Re: Problem connect Mikrotik when using API

Sun Jan 26, 2014 11:35 am

Hi Boen robot Again
Last time I worked with Api by using " require('routeros_api.class.php');."
It can return some useful messages of system/resource/cpu/print.
Connection attempt #1 to 192.168.88.98:8728...<<< [6] /login>>> [5, 39] !done>>> [37, 1]
=ret=7eaf193b9631b738e62963ce55bd18cc<<< [6] /login<<< [11] =name=admin<<< [44]
=response=00768ea637ca8423a50554eb93f038e3fe>>> [5, 1] !done Connected...<<< [26] /system/resource/cpu/print>>>
[3, 49] !re>>> [7, 41] =.id=*1>>> [9, 31] =cpu=cpu0>>> [7, 23] =load=7>>> [6, 16] =irq=0>>> [7, 8] =disk=0>>> [5, 1]
!done Array ( [0] => Array ( [.id] => *1 [cpu] => cpu0 [load] => 7 [irq] => 0 [disk] => 0 ) ) Disconnected...
If I use command in Mikrotik as show in cpu_load.jpg

Question
1.In fact I only need load value (load=7). How do I retreive that value ?
Do you have a good tutorials or useful examples?(similar to API_Pear2 manual last time)
2.How "$ARRAY = $API->parse_response($READ);" does work?


However, I wish to use your API (PEAR2_Net...phar) according to your suggestions.
I have some problems when I tried to use this example showipmac.php as shown in below.
I copied PEAR2_Net_RouterOS-1.0.0b4.phar file in the same directory ( as shown is directory.jpg)with showipmac.php.
I got HTTP 500 internal Server error on screen as shown in error_PEAR.jpg whereas I still run resource.php.
Question.
3.What 's happen about my program or PEAR...phar? I tested among three type of declaraltion
- include_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';
-require_once 'PEAR2/Autoload.php';
-require_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';
noone work at all.
4.In getting started , I should enabled outgoing connection with stram_socket_client().
How do I do?
Please advise;


**************************************************************
showipmac.php
<?php
use PEAR2\Net\RouterOS;
include_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';
/require_once 'PEAR2/Autoload.php';
/require_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';

$client = new RouterOS\Client('192.168.0.1', 'admin','');

$responses = $client->sendSync(new RouterOS\Request('/ip/arp/print'));

foreach ($responses as $response) {
if ($response->getType() === RouterOS\Response::TYPE_DATA) {
echo 'IP: ', $response->getArgument('address'),
' MAC: ', $response->getArgument('mac-address'),
"\n";
}
}
*****************************************************************
resource.php
<?php

require('routeros_api.class.php');

$API = new routeros_api();

$API->debug = true;

if ($API->connect('192.168.88.98', 'admin', '')) { // Change this as necessery

$API->write( '/system/resource/cpu/print');



$READ = $API->read(false);
$ARRAY = $API->parse_response($READ);
print_r($ARRAY);



$API->disconnect();

}

?>
You do not have the required permissions to view the files attached to this post.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Problem connect Mikrotik when using API

Sun Jan 26, 2014 4:16 pm

1.In fact I only need load value (load=7). How do I retreive that value ?
Do you have a good tutorials or useful examples?(similar to API_Pear2 manual last time)
With my client, it's as easy as either
$load = $client->sendSync(
    new RouterOS\Request('/system resource cpu print .proplist=load', RouterOS\Query::where('cpu', 'cpu0'))
)->getArgument('load'); 
or
$util = new RouterOS\Util($client);
$util->changeMenu('/system resource cpu');
$load = $util->get(0, 'load'); 
(in both cases, the value is written to the variable $load)

With that client, after you pass the result from read() to parse_response(), you get an array, in which each property is a key, so you just do $ARRAY['load'].
2.How "$ARRAY = $API->parse_response($READ);" does work?
You can see the exact code on its page. It turns every word into a name/value pair, where each name is the key of an associative array, and the according value is the value for that property.

My client does the same thing automatically, exposing the resulting array with the getArgument() method, without making you explicitly call a method to do the parsing. That's because in 99.99% of the cases, you want to deal with the value, not with the full word. For the 0.01% case, there's the Communicator class.
3.What 's happen about my program or PEAR...phar?
The first problem I see is that you haven't replaced your IP address accordingly. You're using 192.168.88.98, but you've left the IP in the example code of 192.168.0.1. Because the client can't connect, it throws an exception, and because it throws an exception, and it is never caught, this results in a fatal error and error code 500, which IE then represents with a custom error page (sadly).

Try to catch the exception... and fix the IP of course... i.e.
<?php
use PEAR2\Net\RouterOS;
include_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';
/require_once 'PEAR2/Autoload.php';
/require_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';

try {
$client = new RouterOS\Client('192.168.88.98', 'admin', '');
} catch (Exception $e) {
    echo 'Unable to connect and/or login to the router';
} 
4.In getting started , I should enabled outgoing connection with stram_socket_client().
How do I do?
stream_socket_client() is enabled by default. The explicit mention is there because many people use PHP on shared hosts, where this function is disabled for security reasons.

To enable connections with it, you add PHP and/or Apache to your server's firewall(s), as mentioned previously in this topic, and in the notes. You previously disabled your firewall, which achieves the same effect, so that part should be OK. Besides, if the other client is working, then this is definitely not the issue.
 
banatus
newbie
Topic Author
Posts: 34
Joined: Tue Jan 21, 2014 9:35 pm

Re: Problem connect Mikrotik when using API

Sun Jan 26, 2014 6:01 pm

Hi Boen_robot
I still fail to use your API again, even I fixed new ip and add exception command as shown in below.
The display is the same with the previous time "HTTP 500 internal server error "
(I still ran resource.php )
Question
1.Can I debug status of your api like ( API-debug=true)? Do you have any command?
2. Why I did not see any other messages even I put "Exception command"
I should see echo ' Unable to connect ' when I cannot login or
I should see a successful login when I can login?
Here is a latest file (showipmac.php).
Thank you so much again.

<?php
use PEAR2\Net\RouterOS;
include_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';
/require_once 'PEAR2/Autoload.php';
/require_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';

try {
$client = new RouterOS\Client('192.168.88.98', 'admin', '');
} catch (Exception $e) {
echo 'Unable to connect and/or login to the router';
}
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Problem connect Mikrotik when using API

Sun Jan 26, 2014 7:58 pm

2. Why I did not see any other messages even I put "Exception command"
I should see echo ' Unable to connect ' when I cannot login
Yes.
1.Can I debug status of your api like ( API-debug=true)? Do you have any command?
There's nothing "bolted on" (Because it would needlessly hurt performance), although you could always use PHP's tools like var_dump(), XDebug, etc. over $client or any other variable containing a related object.

Exceptions are thrown whenever something is outside of normal protocol flow.

Because an exception was not thrown, it appears the problem is you have PHP 5.2, instead of PHP 5.3 or later. In that case, there's a parser error, which is triggered as soon as the file is included/required.

To be sure, create a new PHP file in the same directory, containing
<?php phpinfo(); ?>
and check the top of its output.

If that's the problem, the solution is to upgrade PHP. PHP 5.2 is long dead anyway.
 
banatus
newbie
Topic Author
Posts: 34
Joined: Tue Jan 21, 2014 9:35 pm

Re: Problem connect Mikrotik when using API

Sun Jan 26, 2014 9:14 pm

Hi
1.According to your suggestion, I am using PHP 5.3.17 as shown in php_ver.jpg
It ensures your API should work with PHP 5.3.17
2. However, I put showmacip.php at the same directory of PEAR file.
3. I found php_error.txt
Here is content, It generated when I execute that script.
[26-Jan-2014 18:45:00 UTC] PHP Parse error: syntax error, unexpected '/' in C:\Apache2\htdocs\showipmac.php on line 4
Here is showmacip.php
<?php
use PEAR2\Net\RouterOS;
include_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';
/require_once 'PEAR2/Autoload.php';
/require_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';

try {
$client = new RouterOS\Client('192.168.88.98', 'admin', '');
} catch (Exception $e) {
echo 'Unable to connect and/or login to the router';
}

4.Thus, I deleted /require_once two lines out and change file to
showcpu.php instead.
Here is showcpu.php
<?php
use PEAR2\Net\RouterOS;
include_once 'PEAR2_Net_RouterOS-1.0.0b4.phar';

try {
$client = new RouterOS\Client('192.168.88.98', 'admin', '');
$util = new RouterOS\Util($client);
$util->changeMenu('/system resource cpu');
$load = $util->get(0, 'load');
echo $util->get(0,'load');

} catch (Exception $e) {
echo 'Unable to connect and/or login to the router';
}
5.I run again , It showed a number that I expected this is cpu load value.
I think it works now.
6.Please explain more about two lines as shown in below.
$load = $util->get(0, 'load');
echo $util->get(0,'load');
Thank you so much
You do not have the required permissions to view the files attached to this post.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Problem connect Mikrotik when using API

Sun Jan 26, 2014 11:16 pm

1.
...
5.
...
Great. I'm glad it worked out, and I apologize for not noticing this simple syntax error.
6.Please explain more about two lines as shown in below.
$load = $util->get(0, 'load');
echo $util->get(0,'load');
The whole Util class is filled with frequently used functionality, abstracted away in single methods. A particular motivator was the inability of the API protocol to accept numbers. In other words, if you try to target an entry in the API like "/system resource cpu get numbers=0 value-name=load", you would get an error, because it doesn't recognize the number "0". You instead need to use the item's ID.

When you first call get() with a number, it fetches all items' IDs. It also takes the first ID returned to be the ID of item with number 0. See the Util class' reference page for details on this, and other Util methods (of which, if you ask me, get() is the least exciting one). Or perhaps see this wiki page if you prefer a more tutorial-ish form.

BTW,
2.There are a lot of documents which I easily find the useful command than PEAR2_Net_RouterOS.
I'm still wondering what documents are we talking about.
 
banatus
newbie
Topic Author
Posts: 34
Joined: Tue Jan 21, 2014 9:35 pm

Re: Problem connect Mikrotik when using API

Mon Jan 27, 2014 5:10 am

Thank you so much Boen_robot
I try to practice for developing more functions soon.
If there are other problems about your api , I wil ask you again.
1.Not sure whether , If I open new cases you will answer or the others do?
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Problem connect Mikrotik when using API

Mon Jan 27, 2014 4:17 pm

1.Not sure whether , If I open new cases you will answer or the others do?
I tend to be the one to answer API questions in general (PHP or otherwise), except if your question is of the "is this supported? I searched and I don't see it..." variety, in which case, of course, the MikroTik staff tends to answer (often with "No", sadly), since only they know for sure.

Personally, I'd prefer it if you make a new topic for a new unrelated issue, since not only are you making it more likely for others to answer, but also, it makes it easier on me to see at a glance what I should brace myself for.

Who is online

Users browsing this forum: tangent and 5 guests