frzb / routeros-api-client
适用于PHP的现代Mikrotik RouterOS API客户端
Requires
- php: >=8.0
- ext-sockets: *
- frzb/ssh: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- larapack/dd: ^1.1
- limedeck/phpunit-detailed-printer: ^5.0
- orchestra/testbench: ^4.0|^5.0
- phpunit/phpunit: ^8.0
- rector/rector: ^0.7|^0.8|^0.9
- roave/security-advisories: dev-master
- squizlabs/php_codesniffer: ^3.5
This package is auto-updated.
Last update: 2024-09-15 17:31:22 UTC
README
RouterOS API客户端
composer require evilfreelancer/routeros-api-php
这个库部分基于这个旧项目,但它有很多创新来简化开发。此外,该项目旨在与符合PSR标准的PHP7/8一起工作。
您可以使用此库与6.43之前和6.43之后的RouterOS固件版本一起使用,它将在连接阶段自动检测。
目录
最低要求
php
>= 7.2|8.0ext-sockets
Laravel框架支持
RouterOS API客户端针对作为正常Laravel包的使用进行了优化,所有功能都可通过\RouterOS
外观访问,要访问客户端对象,您需要使用
$config = new \RouterOS\Config([ 'host' => '192.168.1.3', 'user' => 'admin', 'pass' => 'admin', 'port' => 8728, ]); $client = new \RouterOS\Client($config);
使用外观并将参数数组传递给client
方法
$client = \RouterOS::client([ 'host' => '192.168.1.3', 'user' => 'admin', 'pass' => 'admin', 'port' => 8728, ]);
您还可以获取包含从routeros-api.php
文件中获取的所有配置的数组
$config = \RouterOS::config([ 'host' => '192.168.1.3', 'user' => 'admin', 'pass' => 'admin', 'port' => 8728, ]); dump($config); $client = \RouterOS::client($config);
Laravel安装
默认情况下,包将自动注册其服务提供程序,但如果您是Laravel版本低于5.5的愉快拥有者,那么在项目(当然,在完成composer require
之后)中,将包添加到config/app.php
的providers
块中
'providers' => [ // ... RouterOS\Laravel\ServiceProvider::class, ],
可选地,如果想要更改任何默认值,则发布配置文件
php artisan vendor:publish --provider="RouterOS\\Laravel\\ServiceProvider"
如何使用
基本示例,通过命令行的类似操作是/ip hotspot ip-binding print
use \RouterOS\Client; use \RouterOS\Query; // Initiate client with config object $client = new Client([ 'host' => '192.168.1.3', 'user' => 'admin', 'pass' => 'admin', 'port' => 8728, ]); // Create "where" Query object for RouterOS $query = (new Query('/ip/hotspot/ip-binding/print')) ->where('mac-address', '00:00:00:00:40:29'); // Send query and read response from RouterOS $response = $client->query($query)->read(); var_dump($response);
更新/创建/删除类型查询的基本示例
use \RouterOS\Client; use \RouterOS\Query; // Initiate client with config object $client = new Client([ 'host' => '192.168.1.3', 'user' => 'admin', 'pass' => 'admin' ]); // Send "equal" query with details about IP address which should be created $query = (new Query('/ip/hotspot/ip-binding/add')) ->equal('mac-address', '00:00:00:00:40:29') ->equal('type', 'bypassed') ->equal('comment', 'testcomment'); // Send query and read response from RouterOS (ordinary answer from update/create/delete queries has empty body) $response = $client->query($query)->read(); var_dump($response);
如果您需要从路由器导出所有设置
use \RouterOS\Client; // Initiate client with config object $client = new Client([ 'host' => '192.168.1.3', 'user' => 'admin', 'pass' => 'admin', 'ssh_port' => 22222, 'ssh_timeout' => 60, // if not set then 30 seconds by default ]); // Execute export command via ssh $response = $client->query('/export'); // or $response = $client->export(); var_dump($response);
带有"where"条件、"操作"和"标签"的示例
use \RouterOS\Query; /** * Simple "where" query will be generated by default */ $client->query('/ip/address/print')->read(); /** * Send advanced "where" query with parameters to RouterOS */ // If only one "where" condition $client->query('/queue/simple/print', ['target', '192.168.1.1/32']); // If multiple "where" conditions and need merge (operation "|") results $client->query('/interface/print', [ ['type', 'ether'], // same as ['type', '=', 'ether'] ['type', 'vlan'], // same as ['type', '=', 'vlan'] ], '|'); /** * Or in OOP style */ // If you need create query for "create/update/delete" operations $query = new Query('/ip/hotspot/ip-binding/add'); $query->equal('mac-address', '00:00:00:00:40:29'); $query->equal('type', 'bypassed'); $query->equal('comment', 'testcomment'); // If multiple "where" conditions and need merge (operation "|") results $query = new Query('/interface/print'); $query->where('type', 'ether'); $query->where('type', 'vlan'); $query->operations('|'); // If multiple "where" conditions and need append tag $query = new Query('/interface/set'); $query->where('disabled', 'no'); $query->where('.id', 'ether1'); $query->tag(4); /** * Write Query object to RouterOS and read response from it */ $response = $client->query($query)->read();
您可以在这里找到所有可用的示例。
如何配置客户端
您只需要创建具有所需参数的数组格式的Client类的对象
use \RouterOS\Client; $client = new Client([ 'host' => '192.168.1.3', 'user' => 'admin', 'pass' => 'admin' ]);
ℹ️ Config和Client类的高级用法示例
use \RouterOS\Config; use \RouterOS\Client; /** * You can create object of Config class */ $config = new Config(); // Then set parameters of config $config->set('host', '192.168.1.3'); $config->set('user', 'admin'); $config->set('pass', 'admin'); // By the way, `->set()` method is support inline style of syntax $config ->set('host', '192.168.1.3') ->set('user', 'admin') ->set('pass', 'admin'); /** * Or just create preconfigured Config object */ $config = new Config([ 'host' => '192.168.1.3', 'user' => 'admin', 'pass' => 'admin' ]); /** * Then send Config object to Client constructor */ $client = new Client($config);
可用的配置参数列表
如何启用对旧登录架构(RouterOS 6.43之前)的支持
从0.8.1版本开始,这不再重要,固件版本将自动检测。已弃用,将在1.5.0版本中删除
<?php require_once __DIR__ . '/vendor/autoload.php'; use \RouterOS\Client; // Initiate client with config object $client = new Client([ 'host' => '192.168.1.3', 'user' => 'admin', 'pass' => 'admin', 'legacy' => true // you need set `legacy` parameter with `true` value ]); // Your code below...
如何编写查询
您可以向路由器写入任何查询,为此您需要创建一个"Query"对象,其第一个参数是所需的命令,之后您可以向"Query"对象添加命令的属性。
有关属性和从这些属性创建的"words"的更多信息,请参阅这里。
有关"expressions"、"where"、"equal"和其他查询的筛选/修改的更多信息,请参阅这里。
Query类简单用法示例
use \RouterOS\Query; // Get all installed packages (it may be enabled or disabled) $query = new Query('/system/package/getall'); // Send "equal" query with details about IP address which should be created $query = (new Query('/ip/hotspot/ip-binding/add')) ->equal('mac-address', '00:00:00:00:40:29') ->equal('type', 'bypassed') ->equal('comment', 'testcomment'); // Set where interface is disabled and ID is ether1 (with tag 4) $query = (new Query('/interface/set')) ->where('disabled', 'no') ->where('.id', 'ether1') ->tag(4); // Get all ethernet and VLAN interfaces $query = (new Query('/interface/print')) ->where('type', 'ether') ->where('type', 'vlan') ->operations('|'); // Get all routes that have non-empty comment $query = (new Query('/ip/route/print')) ->where('comment', '>', null);
ℹ️ Query类的高级用法示例
use \RouterOS\Query; use \RouterOS\Client; // Initiate connection to RouterOS $client = new Client([ 'host' => '192.168.1.3', 'user' => 'admin', 'pass' => 'admin' ]); /** * Execute query directly through "->query()" method of Client class */ // If your query has no "where" conditions $client->query('/ip/arp/print'); // If you have only one where condition, you may use one dimensional array as second parameter of query method $client->query('/queue/simple/print', ['target', '192.168.1.250/32']); // If you need set few where conditions then need use multi dimensional array $client->query('/interface/bridge/add', [ ['name', 'vlan100-bridge'], ['vlan-filtering', 'no'] ]); /** * By some reason you may need restrict scope of RouterOS response, * for this need to use third attribute of "->query()" method */ // Get all ethernet and VLAN interfaces $client->query('/interface/print', [ ['type', 'ether'], ['type', 'vlan'] ], '|'); /** * If you want set tag of your query then you need to use fourth * attribute of "->query()" method, but third attribute may be null */ // Enable interface (tag is 4) $client->query('/interface/set', [ ['disabled', 'no'], ['.id', 'ether1'] ], null, 4); /** * Or in OOP style */ // Get all ethernet and VLAN interfaces $query = new Query('/interface/print'); $query->where('type', 'ether'); $query->where('type', 'vlan'); $query->operations('|'); // Enable interface (tag is 4) $query = new Query('/interface/set'); $query->equal('disabled', 'no'); $query->equal('.id', 'ether1'); $query->tag(4); // Or, RAW mode $query = new Query('/interface/set'); $query->add('=disabled=no'); $query->add('=.id=ether1'); $query->add('.tag=4'); // Or, RAW mode in format of array $query = new Query('/interface/set', [ '=disabled=no', '=.id=ether1', '.tag=4' ]); // Or $query = new Query([ '/interface/set', '=disabled=no', '=.id=ether1', '.tag=4' ]); /** * Write Query object to RouterOS and read response from it */ $response = $client->query($query)->read();
将响应作为迭代器读取
默认情况下,此客户端的原解决方案没有针对处理大量结果进行优化,仅针对来自RouterOS API的响应中小量的行数。
但某些路由器可能在其防火墙列表中具有(例如)30000+条记录。特别针对此类任务,已经添加了一个名为readAsIterator
的方法,该方法将路由器获得的结果转换为资源,然后可以对其进行操作。
您可以将响应视为数组,而不使用任何array_*函数。
$response = $client->query($query)->readAsIterator(); var_dump($response); // The following for loop allows you to skip elements for which // $iterator->current() throws an exception, rather than breaking // the loop. for ($response->rewind(); $response->valid(); $response->next()) { try { $value = $response->current(); } catch (Exception $exception) { continue; } # ... }
简短的方法
您可以通过一行代码简化您的代码,并发送然后从套接字读取。
/** * Execute query and read response in ordinary mode */ $response = $client->query($query)->read(); var_dump($response); // Or $response = $client->q($query)->r(); var_dump($response); // Single method analog of lines above is $response = $client->qr($query); var_dump($response); /** * Execute query and read response as Iterator */ $response = $client->query($query)->readAsIterator(); var_dump($response); // Or $response = $client->q($query)->ri(); var_dump($response); // Single method analog of lines above is $response = $client->qri($query); var_dump($response); /** * By the way, you can send few queries to your router without result: */ $client->query($query1)->query($query2)->query($query3); // Or $client->q($query1)->q($query2)->q($query3);
已知问题
无法建立套接字会话,操作超时
此错误表示库无法连接到您的路由器,这可能意味着路由器已关闭(则需要打开),或者API服务未启用。
转到 Mikrotik路由器OS -> IP -> 服务
并启用api
服务。
或通过命令行
/ip service enable api
如何通过API更新/删除/创建某些内容?
您需要使用->equal()
方法而不是Query
类的->where()
方法。
// Create query which should remove security profile $query = new \RouterOS\Query('/interface/wireless/security-profiles/remove'); // It will generate queries, which stared from "?" symbol: $query->where('.id', '*1'); /* // Sample with ->where() method RouterOS\Query Object ( [_attributes:RouterOS\Query:private] => Array ( [0] => ?.id=*1 ) [_operations:RouterOS\Query:private] => [_tag:RouterOS\Query:private] => [_endpoint:RouterOS\Query:private] => /interface/wireless/security-profiles/remove ) */ // So, as you can see, instead of `->where()` need to use `->equal()` // It will generate queries, which stared from "=" symbol: $query->equal('.id', '*1'); /* // Sample with ->equal() method RouterOS\Query Object ( [_attributes:RouterOS\Query:private] => Array ( [0] => =.id=*1 ) [_operations:RouterOS\Query:private] => [_tag:RouterOS\Query:private] => [_endpoint:RouterOS\Query:private] => /interface/wireless/security-profiles/remove ) */
未定义字符(任何非英语语言)
RouterOS不支持国家语言,仅支持英语(以及RouterOS的API)。
您可以通过网络尝试重现它,例如向您的系统中的任何元素添加注释,然后保存并重新加载页面,您将看到无法阅读的字符。
测试
您可以使用我的具有RouterOS的Docker容器中的其他项目,用于在您的计算机上运行单元测试,为此您只需要有Expect、Docker和Docker Compose。
接下来,使用Docker中的RouterOS克隆仓库,并执行docker-compose up -d
,然后您需要通过preconf.tcl脚本预先配置虚拟路由器,该脚本位于routeros-api-php的根目录下。
./preconf.tcl 12223
./preconf.tcl 22223
然后您可以运行测试。
./vendor/bin/phpunit
链接
- 云托管路由器 - 用于您的虚拟机的RouterOS虚拟镜像
- RouterOS手册:API - 如果您想知道什么是疯狂的话