benmenking / routeros-api Goto Github PK
View Code? Open in Web Editor NEWClient API for RouterOS/Mikrotik
Client API for RouterOS/Mikrotik
How can i listen fro stream.
Like get network uses of users.
Hello, i have found trouble (or bug maybe) when parseResponse parsing result of my hotspot user profile on-login script
here the result before i parse it
=on-login=/system scheduler add name="remove-user-$user" interval="1d" on-even="/ip hotspot active remove [find user=$user];/ip hotspot user remove [find name=$user];/system scheduler remove [find name=remove-user-$user]"
and after i parse it with parseResponse, parseResponse remove some of the result and it becomes like this
[on-login] => /system scheduler add name
after i try to look into the routeros_api.class.php
, i found the problem is because parseResponse()
assumed that the regex only had 2 results which are $MATCHES[0][0]
and $MATCHES[0][1]
. but in my case, the regex have more than 2 results, so the results except $MATCHES[0][0]
and $MATCHES[0][1]
are ignored.
ps: i'm not sure about my issue title
Would like to get this apparent "issue" fixed, although I'm not aware of any test cases.
Hello everybody! Do not think what is criticism, but this project has not been updated for many years and after a while it may stop working on a new versions of PHP.
Therefore, I created the same thing, like in this project but for PHP7 and in accordance with PSR standards. So probably my project will be helpful for somebody.
PS. Sorry for this ADS and thanks to you guys for this elegant API client! Without your library, I would never understand how to work with the RouterOS API.
RouterOS API has been changed in recent versions, this will not work anymore. It needs to get updated.
Sometimes you may get infinity loop, when MikroTik has lost a connection to the network right after sent API command.
to prevent the problem you should check socket timed out and brake the loop.
Here is link to the pull of fix the problem mentioned before #62
I can't find this project on packagist. There are many similar project on routeros-api, but as far as I know this project has the latest update and one that is working.
So, could you register this project on packagist?
Hi,
i did a fresh setup of ubuntu 22.04, php 8.1.13
Test Router is ROS 6.43.8. API User has "write" permission.
It seems the connection works since the example below returns "success"
<?php
require('./config.php');
require('./routeros_api.class.php');
$API = new RouterosAPI();
$API->debug = true;
if ($API->connect($ROS_ADDR, $ROS_USER, $ROS_PASS)) {
echo "success";
$API->disconnect();
}else{
echo "unable to connect";
}
?>
But when i try to add a firwall address-list entry nothing happens.
<?php
require('./config.php');
require('./routeros_api.class.php');
$API = new RouterosAPI();
$API->debug = true;
if ($API->connect($ROS_ADDR, $ROS_USER, $ROS_PASS)) {
echo "success";
$API->write("/ip/firewall/address-list/add", array(
"list" => "test_list",
"address" => "1.2.3.4"
));
$API->disconnect();
}else{
echo "unable to connect";
}
?>
I only get the connection in the Mikrotik logs and the following debug output
Connection attempt #1 to 1.1.1.1:8728...
<<< [6] /login
<<< [9] =name=API
<<< [23] =password=API
>>> [5/5] bytes read.
>>> [5, 1]!done
Connected...
success<<< [29] /ip/firewall/address-list/add
^C
I also don't get anything with
$API->write('/ip/firewall/address-list/print', false);
var_dump($API->read());
Hi Ben!!
Is it possible to connect to RB via MAC address ?? with the Routers API.
I need to access RB via MAC to create the first configurations, without the intervention of a technician. This process would be one time, when registering a new RB on the WEB platform that I am creating ....
This code was working for v6.2, but for some reason, it didnt for 6.37.
$ARR=$this->API->createUserAndProfile(Array(
"customer" => "admin",
"name" => ("$username$postfix"),
"password" => ("$username$postfix"),
"numbers" => ("$username$postfix"),
"profile" => $value,
));
public function createUser(Array $data)
{
$this->comm("/tool/user-manager/user/add", $data);
}
public function createProfile(Array $data)
{
$this->comm("/tool/user-manager/user/create-and-activate-profile", $data);
}
public function createUserAndProfile(Array $data){
$this->createUser(array_except($data, ['numbers', 'profile']));
$this->createProfile(array_except($data, ['name', 'password']));
}
This is the response message I got on 6.3+ was unknown parameter
. Please help me in need of solution here 😢 🙏
This library should be PSR-2 compatible for consistency. I see lots of coding sytles in here that should be standardized. Nothing major, just some code clean ups. PSR-2 requires PSR-1 compatibility, and PSR-1 says:
This is only part of PSR-2 cleanup that will "break" things. How do we feel about this?
I'm seeing a lot of this in my devel enviroment:
Warning: fwrite() expects parameter 1 to be resource, boolean given in /var/www/html/scott/rats/mikrotik-api/routeros_api.class.php on line 363
Warning: fwrite() expects parameter 1 to be resource, boolean given in /var/www/html/scott/rats/mikrotik-api/routeros_api.class.php on line 371
Not critical, but something that should be looked at.
I'm attempting to upgrade a router via the API but I'm getting an error. /system/package/update/check-for-updates
fetches information about the current and latest version. I can use that information to determine if there is an upgrade available. When I try and trigger an upgrade with /system/package/update/upgrade
I get "no such command".
I can only assume one of two things:
Hello. As I access the Mikrotik with a Digital Ocean server, I have already released ports 8728 and 8729 and it still does not work .. It gives the error (Unable to establish socket session, Connection timed out)
This is an open issue to discuss doing API calls via SSL with newer versions of RouterOS. Is this something we can support?
Remove all pre-6.45.1 code as the old login has been abandoned by Mikrotik.
Mikrotik reference on new login
Find and replace the "function connect" to fix:
public function connect($ip, $login, $password)
{
for ($ATTEMPT = 1; $ATTEMPT <= $this->attempts; $ATTEMPT++) {
$this->connected = false;
$PROTOCOL = ($this->ssl ? 'ssl://' : '' );
$context = stream_context_create(array('ssl' => array('ciphers' => 'ADH:ALL', 'verify_peer' => false, 'verify_peer_name' => false)));
$this->debug('Connection attempt #' . $ATTEMPT . ' to ' . $PROTOCOL . $ip . ':' . $this->port . '...');
$this->socket = @stream_socket_client($PROTOCOL . $ip.':'. $this->port, $this->error_no, $this->error_str, $this->timeout, STREAM_CLIENT_CONNECT,
if ($this->socket) {
socket_set_timeout($this->socket, $this->timeout);
$this->write('/login', false);
$this->write('=name=' . $login, false);
$this->write('=password=' . $password, true);
$RESPONSE = $this->read(false);
if (isset($RESPONSE[0]) && $RESPONSE[0] == '!done') {
$this->connected = true;
break;
}
fclose($this->socket);
}
sleep($this->delay);
}
if ($this->connected) {
$this->debug('Connected...');
} else {
$this->debug('Error...');
}
return $this->connected;
}
SSL CONNECTION DOESNT WORK (TESTED MT 6.48) ...
That writes that it use anonymous Diffie-Hellman cipher should be used to connect... https://wiki.mikrotik.com/wiki/Manual:API-SSL
Can't understand how to fix that ... (without SSL its works)
$context = stream_context_create(['ssl' => ['ciphers' => 'ADH:ALL', 'verify_peer' => false, 'verify_peer_name' => false]]);
$PROTOCOL = ($this->ssl ? 'ssl://' : '' );
$this->debug('Connection attempt #' . $ATTEMPT . ' to ' . $PROTOCOL . $ip . ':' . $this->port . '...');
$this->socket = @stream_socket_client($PROTOCOL . $ip.':'. $this->port, $this->error_no, $this->error_str, $this->timeout, STREAM_CLIENT_CONNECT,$context);
I get the following error when tring to READ the response from the API.
mb_detect_encoding(): Argument #1 ($string) must be of type string, array given
It appears on function parseResponse
foreach ($PARSED as $lineNumber=>$line) { foreach ($line as $key=>$value) { if (mb_detect_encoding($value) == 'ASCII') { continue; } if (mb_detect_encoding($value) == 'UTF-8') { $PARSED[$lineNumber][$key] = ''; continue; } $PARSED[$lineNumber][$key] = bin2hex($value); } } return $PARSED;
Hi,
When I execute example1.php, I get results from the router so the connection is okay.
However, data is not parsed :
Call to undefined method RouterosAPI::parse_response()
Thanks.
this is my code and its not working.
$API->write('/tool/torch',false);
//$API->write("=interface=vlan3212");
$API->write("=interface=".$rb_interface);
$API->write("=src-address=".$rb_ip);
$ARRAY= $API->read(false);
print_r($ARRAY);
output:
Connection attempt #1 to 10.0.1.1:5891... <<< [6] /login <<< [13] =name=username_api<<< [26] =password=password_api >>> [5/5] bytes read. >>> [5, 1]!done Connected... <<< [11] /tool/torch <<< [19] =interface=vlan3212 <<< [25] =src-address=10.31.126.21 >>> [5/5] bytes read. >>> [5, 40]!trap >>> [31/31] bytes read. >>> [31, 8]=message=no such command prefix >>> [5/5] bytes read. >>> [5, 1]!done Array ( [0] => !trap [1] => =message=no such command prefix [2] => !done ) Disconnected... Disconnected...
Good morning,
i have some problem adding breakline into my mikrotik API for sending a message. I already try to use PHP_EOL
, \n
, \r\n
. There is no luck, the message only prints first line of the message.
Here is my code:
$mikrokit->comm("/tool/sms/send",array(
"port" => "usb1",
"channel" => "0",
"phone-number" => $order->order_phone,
"message" => "[Rakki] Your order detail".PHP_EOL." Origin: ".$order->origin." ".PHP_EOL."Destination: ".$order->destination"
));
Dear friend
Why can't get name on simple queue ?
i try to print torch data
i can successfully do this on mikrotik terminal
but i can't do this in api
here is my code
$API->write('/tool/torch=interface=bridge1');
i'm not sure how to do this
English
hello!! Could you ask a question how would you do these 2 executions PHP to use the api tool to execute this command below?
/tool sniffer packet print where protocol=tcp
/tool sniffer packet print where protocol=udp
Portugues
olá!! poderia tirar uma dúvida como faria essas 2 execução PHP para usar a ferramenta da api para executar esse comando abaixo?
/tool sniffer packet print where protocol=tcp
/tool sniffer packet print where protocol=udp
hi,
i cannot print all bonding/pppoe-client list . /interface/print works.
any clue?
thanks
i want to use this command by php
ip hotspot active print detail where user=username
i try to use this code but i think it wrong
$ARRAY = $API->comm("/ip/hotspot/active/print/detail/where", array( "user" => "username", ));
output message
[message] => no such command prefix
Você conseguiu usar a porta 80 www ?
my script testcode
if ($API->connect($iphost, $userhost, $pass)) {
$API->write('/system/script/run', false);
$API->write('name=testcode');
$API->disconnect();
}
how to run the script? i tried and nothing happened
log debug:
[5, 1]!done Connected... <<< [18] /system/script/run <<< [15] name=testcode Disconnected... Disconnected...
I have tried to connect to the router using the API on Router OS v6.49.6 and it is not working is there an issue or this API is outdated please help.
Hello,
Just discovered your script.
I am unable to login...this is what I get with the debugger turned on: Connection attempt #1 to 192.168.1.1:8728... Connection attempt #2 to 192.168.1.1:8728... Connection attempt #3 to 192.168.1.1:8728... Connection attempt #4 to 192.168.1.1:8728... Connection attempt #5 to 192.168.1.1:8728... Error... Disconnected...
Am I doing something wrong?
Thx
Hello
I want to change one of NAT (num3) from enable to disabled,
This is my code:
$API->write("/ip/firewall/nat/set", false);
$API->write("=disabled=yes", false);
$API->write("=.id=3");
What is wrong?
Thank you
openssl/openssl#8408
Change code for use ADH on new openssl. But bug if use on old versions.
$context = stream_context_create(array('ssl' => array('ciphers' => 'ADH:ALL:@SECLEVEL=0', 'verify_peer' => false, 'verify_peer_name' => false)));
Hello, after upgrade RouterOS 6.45.1 the PHP api class stop working because there is some changes in login procedure - via https://wiki.mikrotik.com/wiki/Manual:API#Initial_login - a lot of admin communities stop working their management scripts and it's reported in mikrotik official forum. It's possible to modify login procedure?
Log info: system, error, critical: login failed for user myAPI from ipaddress via api.
Thank you
For consistency we should probably always close the connection. Should we have a destructor that does this automatically?
Trying to reset the password:
$API->write('/caps-man/security/set',false);
$API->write('=name="security-guest"=',false);
$API->write('=passphrase="g9rBxmkFvpPb"=');
$ARRAY = $API->read(false);
var_dump($ARRAY);
die();
I receive this response:
array(1) {
[0]=>
string(5) "!done"
}
But no password is reset.
In terminal, I run this command:
/caps-man security set security-guest passphrase=g9rBxmkFvpPb
and, as expected, it works.
Not sure if it's a bug, or something I'm missing from the documentation.
See https://wiki.mikrotik.com/wiki/Manual:API#Initial_login
But I'm not sure if it is possible to get ROS version before login. But without this change it won't be possible to use Net_RouterOS with v6.43+
When trying to login using this script with example script I get an error that users cannot log in.
Router OS version: 6.47.6
user admin
all default value with admin/ password.
Here is what showing error PHP output:-
Connection attempt #1 to 192.168.0.101:8728... <<< [6] /login >>> [5/5] bytes read. >>> [5, 39]!done >>> [37/37] bytes read. >>> [37, 1]=ret=ee8d06ab50d811c5585b85ed6680f813 <<< [6] /login <<< [11] =name=admin <<< [44] =response=00e1c156cce9584df31d905a7b7e51c307 >>> [5/5] bytes read. >>> [5, 51]!trap >>> [42/42] bytes read. >>> [42, 8]=message=invalid user name or password (6) >>> [5/5] bytes read. >>> [5, 1]!done Connection attempt #2 to 192.168.0.101:8728... <<< [6] /login >>> [5/5] bytes read. >>> [5, 39]!done >>> [37/37] bytes read. >>> [37, 1]=ret=716166c3b79a21ff465d621341e027c0 <<< [6] /login <<< [11] =name=admin <<< [44] =response=00efb87bc3b99f46337208e5926621672a >>> [5/5] bytes read. >>> [5, 51]!trap >>> [42/42] bytes read. >>> [42, 8]=message=invalid user name or password (6) >>> [5/5] bytes read. >>> [5, 1]!done Connection attempt #3 to 192.168.0.101:8728... <<< [6] /login >>> [5/5] bytes read. >>> [5, 39]!done >>> [37/37] bytes read. >>> [37, 1]=ret=4921be73916280331b4baf6014287c43 <<< [6] /login <<< [11] =name=admin <<< [44] =response=00f23548e823be27d4f4d7b998b1c39741 >>> [5/5] bytes read. >>> [5, 51]!trap >>> [42/42] bytes read. >>> [42, 8]=message=invalid user name or password (6) >>> [5/5] bytes read. >>> [5, 1]!done Connection attempt #4 to 192.168.0.101:8728... <<< [6] /login >>> [5/5] bytes read. >>> [5, 39]!done >>> [37/37] bytes read. >>> [37, 1]=ret=b6e4ed085e839d0c0dd12587477cd15b <<< [6] /login <<< [11] =name=admin <<< [44] =response=0050672a24d04db9151164dbe797d46426 >>> [5/5] bytes read. >>> [5, 51]!trap >>> [42/42] bytes read. >>> [42, 8]=message=invalid user name or password (6) >>> [5/5] bytes read. >>> [5, 1]!done Connection attempt #5 to 192.168.0.101:8728... <<< [6] /login >>> [5/5] bytes read. >>> [5, 39]!done >>> [37/37] bytes read. >>> [37, 1]=ret=ddf457fb409973d1360ccab427c80991 <<< [6] /login <<< [11] =name=admin <<< [44] =response=003df34783a23f7dc61f3bfeb394f27064 >>> [5/5] bytes read. >>> [5, 51]!trap >>> [42/42] bytes read. >>> [42, 8]=message=invalid user name or password (6) >>> [5/5] bytes read. >>> [5, 1]!done Error... Disconnected...
error log from the router:
Topics: system
error
critical
message: login failure for user admin from 192.168.0.100 via API
Hello, i've found a bug on class. The thing is - if there is a symbol = in response from api - parseResponse removes the line from the right after last symbol =.
Let me show you an exaple:
We want to get dns logs. The log itself looks like:
16:50:03 dns,packet id:f504 rd:1 tc:0 aa:0 qr:1 ra:1 QUERY 'no error'
16:50:03 dns,packet question: freelancehunt.com:A:IN
16:50:03 dns,packet answer:
16:50:03 dns,packet freelancehunt.com:A:119=104.25.147.98
16:50:03 dns,packet freelancehunt.com:A:119=104.25.148.98
And after parseResponse [message] of the last 2 entries looks like:
<freelancehunt.com:A:119
<freelancehunt.com:A:119
Which is incorrect.
I use your library btw and I did notice all your examples need updating. e.g. sed -i 's,parse_response,parseResponse,' example*
.
first one:
$this->write($com, ($count===0));
second (query commands need to be send with question mark)
case "?":
$el = "?$k=$v";
third (hang forever):
$last = ($i === $count - 1);
$this->write($el, $last);
$i++;
Hi i tried to connecting my routeOS but return error like this: https://prnt.sc/jy5cj9
Hello, greetings I am from Venezuela, I am looking for a way to understand the code of PEAR2 which I want to see or if you have that version updated since that way I am working on my local server, in which you could help me thank you very much ..
Here my email [email protected]
Gentlemen,
I'm using the API to perform the backup router. At the time of using the fetch command to send via ftp in version 5.26 enters an infinite loop response like this:
<<< [11] / tool / fetch
<<< [22] = IPv4 address =
<<< [9] = mode = ftp
<<< [31] = src-path = 10.7.3.46--26-Nov.src
<<< [20] = user = mikrotik backup
<<< [19] = password = siria 2015
<<< [11] = upload = yes
<<< [41] = dst-path = 10.7.3.46 / 10.7.3.46--26-Nov.rsc
[3/3] bytes read.
[3, 20]! Re
[18/18] bytes read.
[18, 1] = connecting status =
[3/3] bytes read.
[3, 18]! Re
[16/16] bytes read.
[16, 1] = status = finished
[3/3] bytes read.
[3, 18]! Re
[16/16] bytes read.
[16, 1] = status = finished
[3/3] bytes read.
[3, 18]! Re
[16/16] bytes read.
[16, 1] = status = finished
[3/3] bytes read.
[3, 18]! Re
[16/16] bytes read.
[16, 1] = status = finished
This only occurs in versions 5.XX. In version 6 it works correctly.
Thank you.
Follows the command line api:
$api->comm("/tool/fetch", array(
'address' => '111.111.111.111',
'mode' => 'ftp',
'src-path'=> "$arquivo_backup_nome.rsc",
'user' => 'backupmikrotik',
'password'=> 'siria2015',
'upload' => 'yes',
'dst-path'=> "$ipv4/$arquivo_backup_nome.rsc"
));
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.