Community discussions

just joined
Topic Author
Posts: 11
Joined: Thu Sep 01, 2016 3:19 am

Send and run script on routerOS using PHP API Pear2_Net_RouterOS client

Sat Jan 12, 2019 9:22 pm

Hi everyone,

In another topic, we were talking about a solution to

1. First, send a script to router (without executing it)
2. Execute the script you sent in step 1 (in a given time)

The solution follows. The script below store the result of the ping in the "comment" section of the same script, so if you need to read it back from the script on PHP, you can use the proper API methods for that.
use PEAR2\Net\RouterOS;
require_once 'PEAR2_Net_RouterOS-1.0.0b6.phar';

# variable declarations

$device_ip		= '<x.x.x.x>';
$device_login		= '<login>';
$device_password	= '<password>';
$script_name 		= '<script_name>';
$where_to_ping		= '<ip_to_ping>';
$how_many_packets	= <ping_count>;

try {
    $util = new RouterOS\Util(
		$client = new RouterOS\Client($device_ip, $device_login, $device_password));
} catch (Exception $e) {
    die('Unable to connect to device at '.$device_ip.'.');

// First, we send the script to the router using script::prepare
// It only stores the script, but will not execute it

$util->setMenu('/system script')->add(
		'name' 			=> $script_name,
		'comment'		=> 'Test script execution from Boen Mikrotik PHP API',
		'policy'		=> 'read,write,test',
		'source'		=> RouterOS\Script::prepare(
:local pingcount [/ping $where count=$packets]
/system script set [find name=$mynameis] comment="pingcount=$pingcount"

									'mynameis' => $script_name,
									'where' => $where_to_ping,
									'packets' => $how_many_packets

// Now we set the same script in a scheduler to run 2 seconds later

$util->setMenu('/system scheduler')->add(
		'name' => 'big_test',
		'start-time' => date_add($util->getCurrentTime(),date_interval_create_from_date_string("2 seconds"))->format('H:i:s'),
		'on-event' => $script_name

Hope it helps.

Who is online

Users browsing this forum: No registered users and 4 guests