APIPHPclass.docx
- 文档编号:8974422
- 上传时间:2023-02-02
- 格式:DOCX
- 页数:17
- 大小:18.11KB
APIPHPclass.docx
《APIPHPclass.docx》由会员分享,可在线阅读,更多相关《APIPHPclass.docx(17页珍藏版)》请在冰豆网上搜索。
APIPHPclass
ThisisPHPclassforworkingwithRouterOSv3API.Youcantakeit,edititanduseitasyouneed.
NOTE-Theclassasshowndoesnotworkfora)largereplies,andb)settingvalueswhereareturnvalueissentaftera"!
done".Ihavecodedfixesforthesehere[1]andwillupdatethispagewhenotherpeoplehavehadachancetoreview.
Contents
[hide]
∙1Class
∙2Example1
o2.1Output
∙3Example2
o3.1Output
∙4Example3
∙5Example4
∙6Seealso
Class
php
//
//RouterOSAPIclass
//Author:
DenisBasta
//
//read()functionalteredbyNickBarnestotakeintoaccounttheplacing
//ofthe"!
done"replyandalsocorrectcalculationofthereplylength.
///
//read()functionalteredbyBenMenking(ben@);removed
//echostatementthatdumpedbytedatatoscreen
//
///////////////////////////
//Revisedby:
JeremyJefferson()
//January8,2010
//
//Fixedwritefunctioninordertoallowforqueriestobeexecuted
//
classrouteros_api{
var$debug=false;//Showdebuginformation
var$error_no;//Variableforstoringconnectionerrornumber,ifany
var$error_str;//Variableforstoringconnectionerrortext,ifany
var$attempts=5;//Connectionattemptcount
var$connected=false;//Connectionstate
var$delay=3;//Delaybetweenconnectionattemptsinseconds
var$port=8728;//Porttoconnectto
var$timeout=3;//Connectionattempttimeoutanddatareadtimeout
var$socket;//Variableforstoringsocketresource
/**************************************************
*
*************************************************/
functiondebug($text){
if($this->debug)
echo$text."\n";
}
/**************************************************
*
*************************************************/
functionencode_length($length){
if($length<0x80){
$length=chr($length);
}
else
if($length<0x4000){
$length|=0x8000;
$length=chr(($length>>8)&0xFF).chr($length&0xFF);
}
else
if($length<0x200000){
$length|=0xC00000;
$length=chr(($length>>16)&0xFF).chr(($length>>8)&0xFF).chr($length&0xFF);
}
else
if($length<0x10000000){
$length|=0xE0000000;
$length=chr(($length>>24)&0xFF).chr(($length>>16)&0xFF).chr(($length>>8)&0xFF).chr($length&0xFF);
}
else
if($length>=0x10000000)
$length=chr(0xF0).chr(($length>>24)&0xFF).chr(($length>>16)&0xFF).chr(($length>>8)&0xFF).chr($length&0xFF);
return$length;
}
/**************************************************
*
*************************************************/
functionconnect($ip,$login,$password){
for($ATTEMPT=1;$ATTEMPT<=$this->attempts;$ATTEMPT++){
$this->connected=false;
$this->debug('Connectionattempt#'.$ATTEMPT.'to'.$ip.':
'.$this->port.'...');
if($this->socket=@fsockopen($ip,$this->port,$this->error_no,$this->error_str,$this->timeout)){
socket_set_timeout($this->socket,$this->timeout);
$this->write('/login');
$RESPONSE=$this->read(false);
if($RESPONSE[0]=='!
done'){
if(preg_match_all('/[^=]+/i',$RESPONSE[1],$MATCHES)){
if($MATCHES[0][0]=='ret'&&strlen($MATCHES[0][1])==32){
$this->write('/login',false);
$this->write('=name='.$login,false);
$this->write('=response=00'.md5(chr(0).$password.pack('H*',$MATCHES[0][1])));
$RESPONSE=$this->read(false);
if($RESPONSE[0]=='!
done'){
$this->connected=true;
break;
}
}
}
}
fclose($this->socket);
}
sleep($this->delay);
}
if($this->connected)
$this->debug('Connected...');
else
$this->debug('Error...');
return$this->connected;
}
/**************************************************
*
*************************************************/
functiondisconnect(){
fclose($this->socket);
$this->connected=false;
$this->debug('Disconnected...');
}
/**************************************************
*
*************************************************/
functionparse_response($response){
if(is_array($response)){
$PARSED=array();
$CURRENT=null;
foreach($responseas$x){
if(in_array($x,array('!
fatal','!
re','!
trap'))){
if($x=='!
re')
$CURRENT=&$PARSED[];
else
$CURRENT=&$PARSED[$x][];
}
else
if($x !
='!
done'){
if(preg_match_all('/[^=]+/i',$x,$MATCHES))
$CURRENT[$MATCHES[0][0]]=(isset($MATCHES[0][1]) ?
$MATCHES[0][1] :
'');
}
}
return$PARSED;
}
else
returnarray();
}
/**************************************************
*
*************************************************/
functionarray_change_key_name(&$array){
if(is_array($array)){
foreach($arrayas$k=>$v){
$tmp=str_replace("-","_",$k);
$tmp=str_replace("/","_",$tmp);
if($tmp){
$array_new[$tmp]=$v;
}else{
$array_new[$k]=$v;
}
}
return$array_new;
}else{
return$array;
}
}
/**************************************************
*
*************************************************/
functionparse_response4smarty($response){
if(is_array($response)){
$PARSED=array();
$CURRENT=null;
foreach($responseas$x){
if(in_array($x,array('!
fatal','!
re','!
trap'))){
if($x=='!
re')
$CURRENT=&$PARSED[];
else
$CURRENT=&$PARSED[$x][];
}
else
if($x !
='!
done'){
if(preg_match_all('/[^=]+/i',$x,$MATCHES))
$CURRENT[$MATCHES[0][0]]=(isset($MATCHES[0][1]) ?
$MATCHES[0][1] :
'');
}
}
foreach($PARSEDas$key=>$value){
$PARSED[$key]=$this->array_change_key_name($value);
}
return$PARSED;
}
else{
returnarray();
}
}
/**************************************************
*
*************************************************/
functionread($parse=true){
$RESPONSE=array();
while(true){
//Readthefirstbyteofinputwhichgivesussomeorallofthelength
//oftheremainingreply.
$BYTE=ord(fread($this->socket,1));
$LENGTH=0;
//Ifthefirstbitissetthenweneedtoremovethefirstfourbits,shiftleft8
//andthenreadanotherbytein.
//Werepeatthisforthesecondandthirdbits.
//Ifthefourthbitisset,weneedtoremoveanythingleftinthefirstbyte
//andthenreadinyetanotherbyte.
if($BYTE&128){
if(($BYTE&192)==128){
$LENGTH=(($BYTE&63)<<8)+ord(fread($this->socket,1)) ;
}else{
if(($BYTE&224)==192){
$LENGTH=(($BYTE&31)<<8)+ord(fread($this->socket,1)) ;
$LENGTH=($LENGTH<<8)+ord(fread($this->socket,1)) ;
}else{
if(($BYTE&240)==224){
$LENGTH=(($BYTE&15)<<8)+ord(fread($this->socket,1)) ;
$LENGTH=($LENGTH<<8)+ord(fread($this->socket,1)) ;
$LENGTH=($LENGTH<<8)+ord(fread($this->socket,1)) ;
}else{
$LENGTH=ord(fread($this->socket,1)) ;
$LENGTH=($LENGTH<<8)+ord(fread($this->socket,1)) ;
$LENGTH=($LENGTH<<8)+ord(fread($this->socket,1)) ;
$LENGTH=($LENGTH<<8)+ord(fread($this->socket,1)) ;
}
}
}
}else{
$LENGTH=$BYTE;
}
//Ifwehavegotmorecharacterstoread,readthemin.
if($LENGTH>0){
$_="";
$retlen=0;
while($retlen<$LENGTH){
$toread=$LENGTH-$retlen ;
$_.=fread($this->socket,$toread);
$retlen=strlen($_);
}
$RESPONSE[]=$_ ;
$this->debug('>>>['.$retlen.'/'.$LENGTH.'bytesread.');
}
//Ifwegeta !
done,makeanoteofit.
if($_=="!
done")
$receiveddone=true;
$STATUS=socket_get_status($this->socket);
if($LENGTH>0)
$this->debug('>>>['.$LENGTH.','.$STATUS['unread_bytes'].']'.$_);
if((!
$this->connected&& !
$STATUS['unread_bytes'])||
($this->connected&& !
$STATUS['unread_bytes']&&$receiveddone))
break;
}
if($parse)
$RESPONSE=$this->parse_response($RESPONSE);
return$RESPONSE;
}
/**************************************************
*
*************************************************/
functionwrite($command,$param2=true){
if($command){
$data=explode("\n",$command);
foreach($dataas$com){
$com=trim($com);
fwrite($this->socket,$this->encode_length(strlen($com)).$com);
$this->debug('<<<['.strlen($com).']'.$com);
}
if(gettype($param2)=='integer'){
fwrite($this->socket,$this->encode_length(strlen('.tag='.$param2)).'.tag='.$param2.chr(0));
$this->debug('<<<['.strlen('.tag='.$param2).'].tag='.$param2);
}
else
if(gettype($param2)=='boolean')
fwrite($this->socket,($param2 ?
chr(0) :
''));
returntrue;
}
else
returnfalse;
}
functioncomm($com,$arr=array()){
$count=count($arr);
$this->write($com, !
$arr);
$i=0;
foreach($arras$k=>$v){
$el=($k[0]=="?
") ?
"$k=$v" :
"=$k=$v";
$last=($i++==$count-1);
$this->write($el,$last);
}
return$this->read();
}
}
?
>
Example1
php
require('routeros_api.class.php');
$API=newrouteros_api();
$API->debug=true;
if($API->connect('111.111.111.111','LOGIN','PASSWORD')){
$API->write('/interface/getall');
$READ=$API->read(false);
$ARRAY=$API->parse_response($READ);
print_r($ARRAY);
$API->disconnect();
}
?
>
OR
php
require('routeros_api.class.php');
$API=newrouteros_api();
$API->debug=true;
if($API->connect('111.111.111.111','LOGIN','PASSWORD')){
$API->write('/interface/getall');
$ARRAY=$API->read();
print_r($ARRAY);
$API->disconnect();
}
?
>
OR
php
require('routeros_api.class.php');
$API=newrouteros_api();
$API->debug=true;
if($API->conn
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- APIPHPclass