Sie sind auf Seite 1von 12

26/3/2018 Paquete API PHP - MikroTik Wiki

Paquete API PHP


De MikroTik Wiki

Nota: Este es solo uno de los tres clientes de PHP API. Echa un vistazo también a los clientes API por Kamil Trzcinski y Denis Basta

Contenido
1 cliente
1.1 Documentación
1.2 Créditos y material legal
2 ejemplos
2.1 Imprimir registros del enrutador (como texto sin formato)
2.2 Imprimir registros del enrutador (como tabla HTML)
2.3 Ping del enrutador
2.4 Formulario "Cambiar contraseña" para usuarios de hotspot
2.4.1 Bonificación: "Cambiar contraseña" independientemente de la ubicación del servidor web
2.5 Formulario de "contraseña olvidada" para usuarios de hotspot
2.6 Generador de contraseñas de Wi-Fi aleatorio
2.7 Buscador MAC
3 Ver también

Cliente
Los ejemplos en esta página usan el paquete PEAR2_Net_RouterOS (http://pear2.github.com/Net_RouterOS/) . Puede instalarlo con Pyrus, PEAR,
Composer o simplemente descargar el archivo ".phar" e incluirlo desde su archivo PHP .

Nota: A pesar del nombre, PEAR (2) en sí mismo NO es necesario.

https://wiki.mikrotik.com/wiki/API_PHP_package 1/12
26/3/2018 Paquete API PHP - MikroTik Wiki

Nota: El cliente requiere PHP 5.3.0 o posterior.

Note: The client should, in theory, work without any problems for large replies and commands, as well as any and all RouterBOARD devices, but has not
been extensively tested with such. Please report any such experiences (positive or negative ones) at the forums (http://forum.mikrotik.com/).

Documentation
Tutorials for this client are available in its GitHub Wiki (https://github.com/pear2/Net_RouterOS/wiki), including reference docs (https://pear2.github.io/
Net_RouterOS/Documentation/1.0.0b6/), which, if you have a smart PHP IDE like NetBeans, PhpStorm or similar, you can also view alongside its auto-
complete suggestions.

Credits and legal stuff


Author: Vasil Rangelov, a.k.a. boen_robot (boen [dot] robot [at] gmail [dot] com)

License: LGPL 2.1 (http://www.gnu.org/copyleft/lesser.html)

(Summary: Use the library as you like, no requirements or restrictions; If you modify the library and publish an application using that library, also
publish the modified library itself with the original credits preserved and under the same license)

Examples
All examples assume that you used Pyrus or PEAR for installation and have installed PEAR2_Autoload. Also, the router is assumed to be accessible
with a local IP to the device PHP runs from. The client itself could work without these restrictions - they are specified here for clarity and consistency.
https://wiki.mikrotik.com/wiki/API_PHP_package 2/12
26/3/2018 Paquete API PHP - MikroTik Wiki

Note: You should be able to replace "PEAR2/Autoload.php" with the path to the ".phar" file, and have everything "just work".

Print router logs (as plain text)


The following example shows the router's log as plain text (one log entry per line). You should make sure this is not publicly visible, as it may give
potential attackers useful info (especially the parts about a username having logged in by a particular protocol).

<?php
use PEAR2\Net\RouterOS;
require_once 'PEAR2/Autoload.php';

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

try {
$util = new RouterOS\Util($client = new RouterOS\Client('192.168.88.1', 'admin', 'password'));

foreach ($util->setMenu('/log')->getAll() as $entry) {


echo $entry('time') . ' ' . $entry('topics') . ' ' . $entry('message') . "\n";
}
} catch (Exception $e) {
echo 'Unable to connect to RouterOS.';
}

Print router logs (as HTML table)


Same as the previous example, but as an HTML table instead, with the different topics being highlighted in different dotted "boxes".

<?php
use PEAR2\Net\RouterOS;
require_once 'PEAR2/Autoload.php';

?><!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>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>RouterOS log</title>
<style type="text/css">
table, td, th {border: 1px solid black;}
td span {outline: 1px dotted black;}

https://wiki.mikrotik.com/wiki/API_PHP_package 3/12
26/3/2018 Paquete API PHP - MikroTik Wiki
</style>
</head>
<body>
<?php
try {
$util = new RouterOS\Util($client = new RouterOS\Client('192.168.88.1', 'admin', 'password'));
?><table>
<thead>
<tr>
<th>Time</th>
<th>Topics</th>
<th>Message</th>
</tr>
</thead>
<tbody>
<?php foreach ($util->setMenu('/log')->getAll() as $entry) { ?>
<tr>
<td><?php echo $entry('time'); ?></td>
<td>
<?php foreach (explode(',', $entry('topics')) as $topic) { ?>
<span><?php echo $topic; ?></span>
<?php } ?>
</td>
<td><?php echo $entry('message'); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } catch (Exception $e) { ?>
<div>Unable to connect to RouterOS.</div>
<?php } ?>
</body>
</html>

Ping from router


This example is particularly useful when you want to ping someone from inside the network while browsing the page from outside the network.

<?php
use PEAR2\Net\RouterOS;
require_once 'PEAR2/Autoload.php';

if (isset($_GET['act'])) {//This is merely to ensure the form was submitted.

//Adjust RouterOS IP, username and password accordingly.


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

//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.

https://wiki.mikrotik.com/wiki/API_PHP_package 4/12
26/3/2018 Paquete API PHP - MikroTik Wiki
$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('time'), '</li>';
}
echo '</ul></div>';
}
?>
</body>
</html>

"Change password" form for hotspot users


The script assumes you have already made a hotspot and do NOT make this file accessible in a walled garden, i.e. users must be logged in to access it.
For convenience's sake, you may want to link to it from the status page, and make sure the web server's lease is static.

Warning: As clarified earlier on this page, the web server needs to be within the local network of the hotspot. In this case, this is required to distinguish
hotspot users, which would otherwise be accessing the page with the same IP.

https://wiki.mikrotik.com/wiki/API_PHP_package 5/12
26/3/2018 Paquete API PHP - MikroTik Wiki

Warning: The web server too must be logged into the hotspot, in order to be able to access the router. You can create an IP binding for the web server
that is of type "bypassed", in order to avoid having it log in. See hotspot's manual page for details on how to create a binding.

<?php
use PEAR2\Net\RouterOS;
require_once 'PEAR2/Autoload.php';

$errors = array();

try {
//Adjust RouterOS IP, username and password accordingly.
$client = new RouterOS\Client('192.168.88.1', 'admin', 'password');

$printRequest = new RouterOS\Request(


'/ip hotspot active print .proplist=user',
RouterOS\Query::where('address', $_SERVER['REMOTE_ADDR'])
);
$hotspotUsername = $client->sendSync($printRequest)->getProperty('user');
} catch(Exception $e) {
$errors[] = $e->getMessage();
}

if (isset($_POST['password']) && isset($_POST['password2'])) {


if ($_POST['password'] !== $_POST['password2']) {
$errors[] = 'Passwords do not match.';
} elseif (empty($errors)) {
//Here's the fun part - actually changing the password
$setRequest = new RouterOS\Request('/ip hotspot user set');
$client($setRequest
->setArgument('numbers', $hotspotUsername)
->setArgument('password', $_POST['password'])
);
}
}

?><!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>Change your hotspot password</title>
<style type="text/css">
#errors {background-color: darkred; color: white;}
#success {background-color: darkgreen; color: white;}
</style>
</head>
<body>
<div>

https://wiki.mikrotik.com/wiki/API_PHP_package 6/12
26/3/2018 Paquete API PHP - MikroTik Wiki
<?php if (!isset($hotspotUsername)) { ?>
<h1>We're sorry, but we can't change your password right now.
Please try again later</h1>
<?php } else { ?>
<h1>You are currently logged in as "<?php
echo $hotspotUsername;
?>"</h1>

<?php if(!empty($errors)) { ?>


<div id="errors"><ul>
<?php foreach ($errors as $error) { ?>
<li><?php echo $error; ?></li>
<?php } ?>
</ul></div>
<?php } elseif (isset($_POST['password'])) { ?>
<div id="success">Your password has been changed.</div>
<?php } ?>

<form action="" method="post">


<ul>
<li>
<label for="password">New password:</label>
<input type="password" id="password" name="password" value="" />
</li>
<li>
<label for="password2">Confirm new password:</label>
<input type="password" id="password2" name="password2" value="" />
</li>
<li>
<input type="submit" id="act" name="act" value="Change password" />
</li>
</ul>
</form>
<?php } ?>
</div>
</body>
</html>

Bonus: "Change password" regardless of web server location

The above approach for determining the currently logged in user requires for the web server to be inside the local hotspot network. In addition to being
inconvenient (in that you may not want to keep your web server in your network), the approach can also be somewhat error prone, in that users could
access the web server without being logged in, at which point they'd see the same error message as if the router was unavailable, except that it is, it's just
that it can't determine their username... Oh, and the IP binding requirement is a little annoying too.

The approach below detects the hotspot user's cookie, taking the username from it. If the server (or this PHP file at least) is not in a walled garden and
outside the hotspot network, users won't be able to access it without being logged in, ensuring a successful match.

The setup at the router here is the most important bit:

https://wiki.mikrotik.com/wiki/API_PHP_package 7/12
26/3/2018 Paquete API PHP - MikroTik Wiki

1. Make sure the hotspot is available from a domain, even if it's one only the router itself knows, e.g. "router.local".
2. Add a DNS entry for the web server that is in a subdomain of the hotspot's domain, e.g. "panel.router.local".
3. Make sure the web server can actually respond to this domain. With IIS for example, a separate setting is required. With Apache, if you're using
ANY virtual hosts, you'll need to explicitly add this one too.
4. Place the PHP file so that the "path" component of the URL starts with "/login". This could be a dedicated folder at the web server root called
"login", or even just prefixing the name of the file, e.g. "loginChangePassword.php". This last part is required, because the cookies that hotspot
sets have "path=/login" in them, meaning the browser will only give the cookie if the path starts with "/login".

To actually do the matching against a cookie, replace

$printRequest = new RouterOS\Request(


'/ip hotspot active print .proplist=user',
RouterOS\Query::where('address', $_SERVER['REMOTE_ADDR'])
);

with

$printRequest = new RouterOS\Request(


'/ip hotspot cookie print .proplist=user',
RouterOS\Query::where('.id', '*' . strtoupper(base_convert($_COOKIE['loginID'], 10, 16)))
);

You'll notice the ID is available in a cookie called "loginID". The cookie's value is in decimal, and RouterOS internally stores the ID in hex, with "*" to
indicate type "id", which is why we do the conversion (and we use base_convert instead of dechex, because the ID can be up to 64 bits, not just 32 -
dechex's limit).

"Forgotten password" form for hotspot users


The following script needs to be accessible from a server in a walled garden, i.e. users must not need to be logged in to access it. You should link to it
from the login page.

To prevent arbitrary people from resetting passwords, the script here requires users to provide two pieces of personal information: Email, and phone.
The latter is expected to be the "comment" for a user. If both pieces are correct, the password is set to a new password the user defines.

This scheme is used for the sake of simplicity. Depending on the rest of your setup (e.g. if you have a public trial account, or an SMS gateway...), you
may have better ways to deal with confirming the user's identity.

<?php
use PEAR2\Net\RouterOS;
require_once 'PEAR2/Autoload.php';

https://wiki.mikrotik.com/wiki/API_PHP_package 8/12
26/3/2018 Paquete API PHP - MikroTik Wiki

$errors = array();

//Check if the form was submitted. Don't bother with the checks if not.
if (isset($_POST['act'])) {
try {
//Adjust RouterOS IP, username and password accordingly.
$client = new RouterOS\Client('192.168.88.1', 'admin', 'password');
} catch(Exception $e) {
$errors[] = $e->getMessage();
}

if (empty($_POST['email'])) {
$errors[] = 'Email is required.';
}

if (empty($_POST['phone'])) {
$errors[] = 'Phone is required.';
}

if (empty($errors)) {
//Check if this is an imposter or not
$printRequest = new RouterOS\Request('/ip hotspot user print .proplist=.id');
$printRequest->setQuery(
RouterOS\Query::where('email', $_POST['email'])->andWhere('comment', $_POST['phone'])
);
$id = $client->sendSync($printRequest)->getProperty('.id');
if (null === $id) {
$errors[] = 'Email or phone does not match that of any user.';
}
}

if (!isset($_POST['password']) || !isset($_POST['password2'])) {
$errors[] = 'Setting a new password is required.';
}

if (empty($errors)) {
if ($_POST['password'] !== $_POST['password2']) {
$errors[] = 'Passwords do not match.';
} else {
//Here's the fun part - actually changing the password
$setRequest = new RouterOS\Request('/ip hotspot user set');
$client->sendSync($setRequest
->setArgument('password', $_POST['password'])
->setArgument('numbers', $id)
);

//Redirect back to the login page, thus indicating success.


header('Location: http://192.168.88.1/login.html');
}
}
}

?><!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">

https://wiki.mikrotik.com/wiki/API_PHP_package 9/12
26/3/2018 Paquete API PHP - MikroTik Wiki
<head>
<title>Forgot your hotspot password?</title>
<style type="text/css">#errors {background-color: darkred; color: white;}</style>
</head>
<body>
<div>
<h1>You can reset your hotspot password by filling the following form.
You'll be redirected back to the login page once you're done</h1>
<?php if(!empty($errors)) { ?>
<div id="errors"><ul>
<?php foreach ($errors as $error) { ?>
<li><?php echo $error; ?></li>
<?php } ?>
</ul></div>
<?php } ?>
<form action="" method="post">
<ul>
<li>
<label for="email">Email:</label>
<input type="text" id="email" name="email" value="" />
</li>
<li>
<label for="phone">Phone:</label>
<input type="text" id="phone" name="phone" value="" />
</li>
<li>
<label for="password">New password:</label>
<input type="password" id="password" name="password" value="" />
</li>
<li>
<label for="password2">Confirm new password:</label>
<input type="password" id="password2" name="password2" value="" />
</li>
<li>
<input type="submit" id="act" name="act" value="Reset password" />
</li>
</ul>
</form>
</div>
</body>
</html>

Random Wi-Fi password generator


The following script is meant to be ran at a scheduled interval, generating a new Wi-Fi password each time it's ran.

The Wi-Fi password is set at the "default" security profile, which is predefined on RouterBOARD devices with Wi-Fi adapters. Adjust accordingly if not
using that profile.

Note that the provided alphabet below intentionally omits potentially ambiguous characters, such as "0" and "o".

https://wiki.mikrotik.com/wiki/API_PHP_package 10/12
26/3/2018 Paquete API PHP - MikroTik Wiki

<?php
use PEAR2\Net\RouterOS;
require_once 'PEAR2/Autoload.php';

try {
//Adjust RouterOS IP, username and password accordingly.
$client = new RouterOS\Client('192.168.88.1', 'admin', 'password');

//Configuration for password generation


$passAlphabet = 'abcdefghikmnpqrstuvxyz23456789';
$passLength = 8;

//Password generation procedure


$passAlphabetLimit = strlen($passAlphabet)-1;
$pass = '';
for ($i = 0; $i < $passLength; ++$i) {
$pass .= $passAlphabet[mt_rand(0, $passAlphabetLimit)];
}

//Password generated; stored in pass $pass; Now set it on the router


$setRequest = new RouterOS\Request(
'/interface wireless security-profiles set numbers=default'
);
$setRequest
->setArgument('wpa-pre-shared-key', $pass)
->setArgument('wpa2-pre-shared-key', $pass);
$client->sendSync($setRequest);

echo 'New Wi-Fi password: ', $pass;


exit(0);
} catch (Exception $e) {
echo $e;
exit(1);
}

MAC finder
Tired of asking your customers to tell you their MAC address (and go over the same "click here and..." instructions over and over again)? Well, using the
following script, you can now... switch the insructions to "go to this web page... by clicking here and...":

<?php
use PEAR2\Net\RouterOS;
require_once 'PEAR2/Autoload.php';

?><!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>

https://wiki.mikrotik.com/wiki/API_PHP_package 11/12
26/3/2018 Paquete API PHP - MikroTik Wiki
<body>
<h1>
<?php
try {
//Adjust RouterOS IP, username and password accordingly.
$client = new RouterOS\Client('192.168.88.1', 'admin', 'password');

$printRequest = new RouterOS\Request('/ip arp print .proplist=mac-address');


$printRequest->setQuery(
RouterOS\Query::where('address', $_SERVER['REMOTE_ADDR'])
);
$mac = $client->sendSync($printRequest)->getProperty('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>

See also
Protocolo API
Presentación de MUM BG 2014 ( Video en búlgaro (https://www.youtube.com/watch?v=vbkOBdJH2qw) , diapositivas en inglés (http://www.slid
eshare.net/boen_robot/the-better-php-api) y búlgaro (http://www.slideshare.net/boen_robot/the-better-php-api-bg) )

Obtenido de " https://wiki.mikrotik.com/index.php?title=API_PHP_package&oldid=29312 "

Categoría : API

Esta página fue editada por última vez el 27 de mayo de 2017, a las 15:14.

https://wiki.mikrotik.com/wiki/API_PHP_package 12/12

Das könnte Ihnen auch gefallen