PHP code example of redrodrigo / router-os-sdk

1. Go to this page and download the library: Download redrodrigo/router-os-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

redrodrigo / router-os-sdk example snippets


use RouterOS\Sdk\Client;

$client = Client::connect([
    'host' => '192.168.88.1',
    'user' => 'admin',
    'pass' => 'secret',
    'tls'  => true, // port defaults to 8729 when true, 8728 otherwise
]);

// One-shot command
$interfaces = $client->write('/interface/print');

// Event-driven stream — one payload per change
$arpChannel = $client->listen('/ip/arp/listen');
while ($row = $arpChannel->wait()) {
    // e.g. ['address' => '10.0.0.5', 'mac-address' => '...']
}

// =interval=N push stream, for print commands with no /listen variant
$resources = $client->interval('/system/resource/print', 2);
while ($cycle = $resources->wait()) {
    // full snapshot every 2 seconds
}

$client->close();

use RouterOS\Sdk\Query;

$query = new Query('/interface/print');
$query->where('disabled', 'false')
      ->where('running', '=', 'true');

$running = $client->query($query);

$secret = $client->findOne('/ppp/secret', ['name' => 'joao']);      // first match, or null
$secrets = $client->findWhere('/ppp/secret', ['service' => 'pppoe']); // all matches
$client->removeWhere('/ppp/secret', ['name' => 'joao']);              // find + /remove each match
$client->setWhere('/ppp/secret', ['name' => 'joao'], ['profile' => 'vip']); // find + /set each match

// PPPoE secrets + active sessions
$client->pppSecrets()->create('joao', 'senha123', profile: 'default');
$client->pppSecrets()->isOnline('joao');
$client->pppSecrets()->kill('joao'); // drop the session so it reconnects with fresh RADIUS/profile attrs
$client->pppSecrets()->remove('joao');

// Firewall address-list, e.g. blocking delinquent customers
$morosos = $client->addressList('morosos');
$morosos->block('10.0.0.5', comment: 'Contract #123'); // idempotent — no duplicate entry on retry
$morosos->isBlocked('10.0.0.5');
$morosos->unblock('10.0.0.5');

// Bandwidth shaping — flat (SimpleQueue) or hierarchical (QueueTree)
$client->simpleQueue()->create('joao', '10.0.0.5/32', '20M/20M');
$client->simpleQueue()->setMaxLimit('joao', '5M/5M');
$client->queueTree()->create('joao', parent: 'total-download', packetMark: 'joao-mark', maxLimit: '20M');

// PPP profiles (rate-limit templates secrets reference)
$client->pppProfiles()->create('vip', rateLimit: '50M/50M');

// Idempotent firewall rule installation, keyed by comment
$client->firewall()->ensureRule('filter', [
    'chain'            => 'forward',
    'src-address-list' => 'morosos',
    'action'           => 'drop',
], comment: 'block-morosos'); // no-op if a rule with this comment already exists

// Unified suspend/activate: each action (address/PPP/queue) runs
// independently, so one failing (e.g. the queue doesn't exist) doesn't
// stop the others — you get back exactly what succeeded and what failed.
$result = $client->customer('joao')->suspend(address: '10.0.0.5', pppUser: 'joao', queueName: 'joao');
$result->succeeded; // e.g. ['address_list', 'ppp_disabled']
$result->failed;    // e.g. ['queue_disabled' => 'no such item']
$client->customer('joao')->activate(address: '10.0.0.5', pppUser: 'joao', queueName: 'joao');

use RouterOS\Sdk\Vpn\WireGuard;

$wg = $client->wireGuard('to-hq');
$wg->createInterface(listenPort: 51820); // RouterOS generates a keypair if none given
$wg->addPeer(
    publicKey: 'base64-hub-public-key',
    allowedAddress: '10.200.0.2/32',
    endpointHost: 'vpn.example.com',
    endpointPort: 51820,
);

use RouterOS\Sdk\Diagnostics\ConnectionProbe;

$result = ConnectionProbe::probe([
    'host' => '192.168.88.1',
    'user' => 'admin',
    'pass' => 'secret',
    'tls'  => true,
]);

$result->status;      // ConnectionStatus::Connected|AuthFailed|Timeout|TlsFailed|Unreachable
$result->isConnected(); // bool
$result->identity;    // router identity (from /system/identity/print), or null

use RouterOS\Sdk\Integrations\Laravel\Facade as RouterOs;

$interfaces = RouterOs::write('/interface/print');            // default connection
$interfaces = RouterOs::connection('secondary')->write(...);  // named connection

use RouterOS\Sdk\Integrations\Laravel\RouterOsManager;

app(RouterOsManager::class)->registerConnection("equipment-{$equipment->id}", [
    'host' => $equipment->ip_address,
    'user' => $equipment->api_user,
    'pass' => $equipment->api_pass,
    'port' => $equipment->api_port,
]);

RouterOs::connection("equipment-{$equipment->id}")->write(...);

use RouterOS\Sdk\ManagedClient;

$managed = new ManagedClient($config);

$managed->onConnected(function ($client) {
    $arp = $client->listen('/ip/arp/listen');
    while (true) {
        $row = $arp->wait(); // throws when the connection dies, ending this cycle
        // handle $row
    }
});

$managed->onDisconnected(function () {
    // e.g. log it — a reconnect (with backoff) is about to be attempted
});

$managed->run(); // blocks until $managed->stop() is called

use RouterOS\Sdk\Client;
use RouterOS\Sdk\Io\Reactor;

$reactor = new Reactor();
$client  = Client::connect($config, $reactor);
bash
php artisan vendor:publish --provider="RouterOS\Sdk\Integrations\Laravel\ServiceProvider" --tag=config