Работаем с Router OS через API
Задача: организовать блокировку абонентов по «балансу», установка скорости интернета абонента, защита от «ручных IP». Биллинг: Lanbilling, Железка: Router OS
- Блокировка по «балансу»
<code>#!/usr/local/bin/php
<?php
include_once ('mikrotic_api.php');
include_once ('sql_new.php');
$bserver = "15634634564"; // сервер НОС
$bname = "bdfbrt";
$bpass = "reber";
$bbase = "erbertberb";
$fl = fopen("/tmp/setspeed.lock", "w");
if( ! ( $fl && flock( $fl, LOCK_EX | LOCK_NB ) ) ) {die("--копия скрипта уже запущена!");};
$lb = new Tsql();
$lb->connect($bserver, $bname, $bpass, $bbase, '-пытаюсь соедениться с базой настроек');
$goodbill=array();
$sql="select vgroups.vg_id,vgroups.archive,vgroups.login,vgroups.blocked,vgroups.current_shape,inet_ntoa(CONV(RIGHT(HEX(staff.segment), 8),16,10)) as ip from vgroups inner join staff on vgroups.vg_id=staff.vg_id where uid in (select uid from usergroups_staff where group_id=8) and vgroups.archive=0 and vgroups.blocked=0";
$res = $lb->ExecuteSQL($sql);
while($row = $lb->mysql_fetch($res)) {
$goodbill[]=$row["ip"];
};
$API = new RouterosAPI();
$API->debug = true;
$goodmik=array();
if ($API->connect("456345634568", "billing", "ebgedbr,rgzrd,terbvertgber")) {
$ARRAYLIST=$API->comm("/ip/firewall/address-list/print",array('without-paging'=>true));
foreach ($ARRAYLIST as $key => $value) {
if ($value["list"]=='good'){
$goodmik[$key]=$value["address"];
};
};
//удаляем
$key_dell="";
foreach ($goodmik as $key=>$ip) {
if (in_array($ip, $goodbill)==false){
$key_dell=$key_dell."$key,";
};
};
if ($key_dell!=""){
$res=$API->comm("/ip/firewall/address-list/remove",array('numbers'=>"$key"));
};
//добавляем
foreach ($goodbill as $ip) {
if (in_array($ip, $goodmik)==false){
$res=$API->comm("/ip/firewall/address-list/add",array('list'=>"good","address"=>"$ip"));
};
};
var_dump($ARRAYLIST);
//выборка по мас
// $arrmacip=array();
// $sql="select vgroups_addons_vals.str_value as mac,vgroups.vg_id,vgroups.archive,vgroups.login,vgroups.blocked,vgroups.current_shape,inet_ntoa(CONV(RIGHT(HEX(staff.segment), 8),16,10)) as ip from vgroups inner join staff on vgroups.vg_id=staff.vg_id inner join vgroups_addons_vals on vgroups_addons_vals.vg_id=vgroups.vg_id where uid in (select uid from usergroups_staff where group_id=8) and vgroups.archive=0 and vgroups_addons_vals.name='mac_babaevo' and vgroups_addons_vals.str_value<>''";
// $res = $lb->ExecuteSQL($sql);
// while($row = $lb->mysql_fetch($res)) {
// $arrmacip[$row["ip"]]=strtoupper($row["mac"]);
// };
// // $arrmacip["1.2.3.4"]=strtoupper("98:EE:CB:43:AA:AA");
// //var_dump($arrmacip);
//
// //читаю текущие значения
// $ARRAYLIST=$API->comm("/ip/arp/print",array('without-paging'=>true));
// var_dump($ARRAYLIST);
//
// //добавляю новые из биллинга
// foreach ($arrmacip as $ip_bill => $mac_bill) {
// //echo "$ip_bill => $mac_bill \n";
// $flag=0; //не найдено
// foreach ($ARRAYLIST as $id => $arrmic) {
// if (($arrmic["address"]==$ip_bill) and ($arrmic["mac-address"]==$mac_bill) and ($arrmic["interface"]=="bridge1")){$flag=1;};
// };
// if ($flag==0){
// echo "--add $ip_bill => $mac_bill\n";
//// $wr=$API->comm("/ip/arp/add",array('address'=>"$ip_bill","mac-address"=>"$mac_bill","interface"=>"bridge1"));
// };
// };
// //удаляю из микротика, если нет в биллинге
// $numbers="";
// foreach ($ARRAYLIST as $id => $arrmic) {
// $flag=0; //не найдено
// foreach ($arrmacip as $ip_bill => $mac_bill) {
// if (($arrmic["address"]==$ip_bill) and ($arrmic["mac-address"]==$mac_bill)){$flag=1;};
// };
// if (($flag==0) and ($arrmic["interface"]!="ether2")){
// $numbers=$numbers.$id.",";
// break;
// };
// };
// echo "delete:";
// echo "--delete $numbers\n";
//// $wr=$API->comm("/ip/arp/remove",array('numbers'=>"$numbers"));
} else {
echo "Нет соединения с микротиком";
};
?></code>
2) Установка скорости
<code>#!/usr/local/bin/php
<?php
include_once ('mikrotic_api.php');
include_once ('sql_new.php');
$bserver = "25354352"; // сервер НОС
$bname = "5234523452";
$bpass = "виапивапи";
$bbase = "пиапвапиав";
$fl = fopen("/tmp/setspeed.lock", "w");
if( ! ( $fl && flock( $fl, LOCK_EX | LOCK_NB ) ) ) {
die("--копия скрипта уже запущена!");
};
$lb = new Tsql();
$lb->connect($bserver, $bname, $bpass, $bbase, '-пытаюсь соедениться с базой настроек');
$API = new RouterosAPI();
$API->debug = true;
if ($API->connect("811125123512", "викупива", "5е235е2,rgzrd,25е2435емы")) {
$ARRAYLIST=$API->comm("/queue/simple/print",array('without-paging'=>true));
//$READ = $API->read(false);
//$ARRAY = $API->parseResponse($READ);
var_dump($ARRAYLIST);
//Добавляем очереди
$sql="select vgroups.vg_id,vgroups.archive,vgroups.login,vgroups.blocked,vgroups.current_shape,inet_ntoa(CONV(RIGHT(HEX(staff.segment), 8),16,10)) as ip from vgroups inner join staff on vgroups.vg_id=staff.vg_id where uid in (select uid from usergroups_staff where group_id=8) and vgroups.archive=0";
echo "$sql\n";
$res = $lb->ExecuteSQL($sql);
while($row = $lb->mysql_fetch($res)) {
$vg_id=$row["vg_id"];
$archive=$row["archive"];
$login=$row["login"];
$blocked=$row["blocked"];
$current_shape=$row["current_shape"]*1000;
$current_shape=$current_shape."/".$current_shape;
$ip=$row["ip"];
$flag=0;
foreach ($ARRAYLIST as $key => $value) {
if ($value["target"]=="$ip/32"){
$flag=1;
//если изменилась скорость, то удаляем!
if ($value["max-limit"]!="$current_shape"){
$ARRAY=$API->comm("/queue/simple/remove",array('numbers'=>"$key"));
$flag=0;
};
};
};
//добавить
if ($flag==0){
$ARRAY=$API->comm("/queue/simple/add",array('limit-at'=>"$current_shape","max-limit"=>"$current_shape","target"=>"$ip/32",'name'=>"$login"));
};
};
//теперь удаляем тех, кого нет в списке!
$keystodell="";
foreach ($ARRAYLIST as $key => $value) {
$login=$value["name"];
$sql="select vgroups.vg_id,vgroups.archive,vgroups.login,vgroups.blocked,vgroups.current_shape,inet_ntoa(CONV(RIGHT(HEX(staff.segment), 8),16,10)) as ip from vgroups inner join staff on vgroups.vg_id=staff.vg_id where uid in (select uid from usergroups_staff where group_id=8) and vgroups.archive=0 and vgroups.login='$login'";
//echo "$sql\n";
$res = $lb->ExecuteSQL($sql);
$cnt=0;
while($row = $lb->mysql_fetch($res)) {$cnt=1;};
if ($cnt==0){
$keystodell=$keystodell."$key,";
};
};
if ($keystodell!=""){
$ARRAY=$API->comm("/queue/simple/remove",array('numbers'=>"$key"));
};
// $ARRAY=$API->comm("/queue/simple/remove",array('numbers'=>"0"));
// var_dump($ARRAY);
// $ARRAY=$API->comm("/queue/simple/add",array('limit-at'=>"25M/25M","max-limit"=>"25M/25M","target"=>'10.30.100.97/32','name'=>"billing","place-before"=>0));
// var_dump($ARRAY);
//$ARRAY=$API->write("/queue/simple/remove queue192");
} else {
echo "Нет соединения с микротиком";
};</code>
3) Актуализация ARP таблицы
<code>#!/usr/local/bin/php
<?php
include_once ('mikrotic_api.php');
include_once ('sql_new.php');
$bserver = "24352345234"; // сервер НОС
$bname = "ивапив";
$bpass = "апивпи";
$bbase = "вапивапивап";
$fl = fopen("/tmp/setspeed.lock", "w");
if( ! ( $fl && flock( $fl, LOCK_EX | LOCK_NB ) ) ) {die("--копия скрипта уже запущена!");};
$lb = new Tsql();
$lb->connect($bserver, $bname, $bpass, $bbase, '-пытаюсь соедениться с базой настроек');
$API = new RouterosAPI();
$API->debug = true;
if ($API->connect("234523452345", "вапиапи", "апивапивап,вапивпивап,ыапивпва")) {
//выборка по ip/мас из биллинга
$arrmacip=array();
$arripbill=array();
$arripbill[]="81.211.92.237"; //ip исключения
$sql="select vgroups_addons_vals.str_value as mac,vgroups.vg_id,vgroups.archive,vgroups.login,vgroups.blocked,vgroups.current_shape,inet_ntoa(CONV(RIGHT(HEX(staff.segment), 8),16,10)) as ip from vgroups inner join staff on vgroups.vg_id=staff.vg_id inner join vgroups_addons_vals on vgroups_addons_vals.vg_id=vgroups.vg_id where uid in (select uid from usergroups_staff where group_id=8) and vgroups.archive=0 and vgroups_addons_vals.name='mac_babaevo' and vgroups_addons_vals.str_value<>''";
$res = $lb->ExecuteSQL($sql);
while($row = $lb->mysql_fetch($res)) {
$arrmacip[$row["ip"]]=strtoupper($row["mac"]);
$arripbill[]=$row["ip"];
};
//выборка по ip/мас из микротика
$ARRAYLIST=$API->comm("/ip/arp/print",array('without-paging'=>true,"where"=>'complete'));
var_dump($ARRAYLIST);
//ищем IP которые нужно удалить с микротика..
$keystodell="";
$arpipmik=array();
foreach ($ARRAYLIST as $key => $values) {
$address=$values["address"];
$arpipmik[]=$address;
$mac=$values["mac-address"];
$dynamic=$values["dynamic"];
if ((in_array($address,$arripbill)==false) and ($mac!="") and ($dynamic=='false')){
echo "-в биллинге такого IP нет ($key)! $address (mac: $mac)\n";
$wr=$API->comm("/ip/arp/remove",array('numbers'=>"$key"));
$keystodell=$keystodell."$key,";
};
};
if ($keystodell!=""){
$keystodell = substr($keystodell,0,-1);
$wr=$API->comm("/ip/arp/remove",array('numbers'=>"$numbers"));
};
//теперь ищем тех, кого нужно добавить
foreach ($arripbill as $ipbill) {
if (in_array($ipbill, $arpipmik)==false){
echo "-добавляем $ipbill\n";
$mac_bill=$arrmacip[$ipbill];
$wr=$API->comm("/ip/arp/add",array('address'=>"$ipbill","mac-address"=>"$mac_bill","interface"=>"bridge1"));
};
};
};</code>