Página 1 de 2 12 ÚltimoÚltimo
+ Responder ao Tópico



  1. #1

    Padrão Mikrotik API !

    Boa noite!

    Galera ea minha primeira vez aqui no fórum!
    Estou estudando um pouco do mikrotik e tive uma ideia!

    Queria fazer uma pagina Externa em PHP para adicionar clientes no Arp ou na Queues do Mikrotik.
    Através de uma conexão via PHP, mais pelo que pesquisei existe um tal de API para isso funcionar!

    Como instalo esse API e onde instalo? e como faço para uma pagina externa acessa-lo?

    Obrigado pela atenção

    Boa noite!

  2. #2
    Avatar de shuttner
    Ingresso
    Aug 2008
    Localização
    Boa Vista - Roraima
    Posts
    257
    Posts de Blog
    1

    Padrão Re: Mikrotik API !

    na própria documentação da api tem exemplos de uso e como colocar no projeto.
    trata apenas de um arquivo php

  3. #3

    Padrão Re: Mikrotik API !

    Obrigado pela resposta amigo só que eu ja li o forum todo do mk e nao achei como inserir as Apis onde ela e colocada para funcionar, entendeu? Abraços

  4. #4
    Avatar de shuttner
    Ingresso
    Aug 2008
    Localização
    Boa Vista - Roraima
    Posts
    257
    Posts de Blog
    1

    Padrão Re: Mikrotik API !

    vc sabe programar em php pelo menos?
    http://wiki.mikrotik.com/wiki/API_PHP_class

  5. #5

    Padrão Re: Mikrotik API !

    Primeiro crie um servidor de testes e depois é so testar os fontes.

  6. #6

    Padrão Re: Mikrotik API !

    Sim sei sim! Minha duvida é se eu vou criar um servidor local com os arquivos php ou eu vou colocar eles dentro do Mikrotik. Eu quero saber onde colocar os arquivos juntos com o API

  7. #7
    Avatar de shuttner
    Ingresso
    Aug 2008
    Localização
    Boa Vista - Roraima
    Posts
    257
    Posts de Blog
    1

    Padrão Re: Mikrotik API !

    baixe a api acima e ative a api no mikrotik
    a api do é só um arquivo .php
    ip -> services

    no endereço acima tem os exemplo, só seguir

  8. #8

    Padrão Re: Mikrotik API !

    também gostaria de fazer isso, mas não entendi direito alguém poderia postar algum passo a passo em português de como eu faço pra add esse bando de dados! ficarei muito grato.

  9. #9

    Padrão Re: Mikrotik API !

    Galera, estou iniciando tambem no mundo API mikrotik.
    Consegui umas classes JAVA para conectar ao mikrotik e buscar informações.

    O Grande lance agora é que por ex. eu faço um comando /ip/hotspot/user/print
    eu obtenho de retorno uma string com todas as informações dos usuarios.

    Preciso de uma classe que trata esta string e cria objetos JAVA com atributos.

    Alguém tem algo pronto?

  10. #10
    Avatar de shuttner
    Ingresso
    Aug 2008
    Localização
    Boa Vista - Roraima
    Posts
    257
    Posts de Blog
    1

    Padrão Re: Mikrotik API !

    Não sei onde pessoal ta achando difícil.
    No caso do PHP, vocês tem que salvar a classe routeros_api num arquivo php (coisa extremamente difícil que não estão entendendo, então fica a dica da mágica), de preferência coloque o arquivo da classe de conexão no mesmo local onde você vai criar o outro arquivo a ser criado.

    <?php
    /*****************************
    *
    * RouterOS PHP API class v1.5
    * Author: Denis Basta
    * Contributors:
    * Nick Barnes
    * Ben Menking (ben [at] infotechsc [dot] com)
    * Jeremy Jefferson (http://jeremyj.com)
    * Cristian Deluxe (djcristiandeluxe [at] gmail [dot] com)
    *
    * http://www.mikrotik.com
    * http://wiki.mikrotik.com/wiki/API_PHP_class
    *
    ******************************/


    class routeros_api
    {
    var $debug = false; // Show debug information
    var $error_no; // Variable for storing connection error number, if any
    var $error_str; // Variable for storing connection error text, if any
    var $attempts = 5; // Connection attempt count
    var $connected = false; // Connection state
    var $delay = 3; // Delay between connection attempts in seconds
    var $port = 8728; // Port to connect to
    var $timeout = 3; // Connection attempt timeout and data read timeout
    var $socket; // Variable for storing socket resource

    /**
    * Print text for debug purposes
    *
    * @param string $text Text to print
    *
    * @return void
    */
    function debug($text)
    {
    if ($this->debug)
    echo $text . "\n";
    }


    /**
    *
    *
    * @param string $length
    *
    * @return void
    */
    function encode_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;
    }


    /**
    * Login to RouterOS
    *
    * @param string $ip Hostname (IP or domain) of the RouterOS server
    * @param string $login The RouterOS username
    * @param string $password The RouterOS password
    *
    * @return boolean If we are connected or not
    */
    function connect($ip, $login, $password)
    {
    for ($ATTEMPT = 1; $ATTEMPT <= $this->attempts; $ATTEMPT++) {
    $this->connected = false;
    $this->debug('Connection attempt #' . $ATTEMPT . ' to ' . $ip . ':' . $this->port . '...');
    $this->socket = @fsockopen($ip, $this->port, $this->error_no, $this->error_str, $this->timeout);
    if ($this->socket) {
    socket_set_timeout($this->socket, $this->timeout);
    $this->write('/login');
    $RESPONSE = $this->read(false);
    if ($RESPONSE[0] == '!done') {
    $MATCHES = array();
    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;
    }


    /**
    * Disconnect from RouterOS
    *
    * @return void
    */
    function disconnect()
    {
    fclose($this->socket);
    $this->connected = false;
    $this->debug('Disconnected...');
    }


    /**
    * Parse response from Router OS
    *
    * @param array $response Response data
    *
    * @return array Array with parsed data
    */
    function parse_response($response)
    {
    if (is_array($response)) {
    $PARSED = array();
    $CURRENT = null;
    $singlevalue = null;
    foreach ($response as $x) {
    if (in_array($x, array(
    '!fatal',
    '!re',
    '!trap'
    ))) {
    if ($x == '!re') {
    $CURRENT =& $PARSED[];
    } else
    $CURRENT =& $PARSED[$x][];
    } else if ($x != '!done') {
    $MATCHES = array();
    if (preg_match_all('/[^=]+/i', $x, $MATCHES)) {
    if ($MATCHES[0][0] == 'ret') {
    $singlevalue = $MATCHES[0][1];
    }
    $CURRENT[$MATCHES[0][0]] = (isset($MATCHES[0][1]) ? $MATCHES[0][1] : '');
    }
    }
    }
    if (empty($PARSED) && !is_null($singlevalue)) {
    $PARSED = $singlevalue;
    }
    return $PARSED;
    } else
    return array();
    }


    /**
    * Parse response from Router OS
    *
    * @param array $response Response data
    *
    * @return array Array with parsed data
    */
    function parse_response4smarty($response)
    {
    if (is_array($response)) {
    $PARSED = array();
    $CURRENT = null;
    $singlevalue = null;
    foreach ($response as $x) {
    if (in_array($x, array(
    '!fatal',
    '!re',
    '!trap'
    ))) {
    if ($x == '!re')
    $CURRENT =& $PARSED[];
    else
    $CURRENT =& $PARSED[$x][];
    } else if ($x != '!done') {
    $MATCHES = array();
    if (preg_match_all('/[^=]+/i', $x, $MATCHES)) {
    if ($MATCHES[0][0] == 'ret') {
    $singlevalue = $MATCHES[0][1];
    }
    $CURRENT[$MATCHES[0][0]] = (isset($MATCHES[0][1]) ? $MATCHES[0][1] : '');
    }
    }
    }
    foreach ($PARSED as $key => $value) {
    $PARSED[$key] = $this->array_change_key_name($value);
    }
    return $PARSED;
    if (empty($PARSED) && !is_null($singlevalue)) {
    $PARSED = $singlevalue;
    }
    } else {
    return array();
    }
    }


    /**
    * Change "-" and "/" from array key to "_"
    *
    * @param array $array Input array
    *
    * @return array Array with changed key names
    */
    function array_change_key_name(&$array)
    {
    if (is_array($array)) {
    foreach ($array as $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;
    }
    }


    /**
    * Read data from Router OS
    *
    * @param boolean $parse Parse the data? default: true
    *
    * @return array Array with parsed or unparsed data
    */
    function read($parse = true)
    {
    $RESPONSE = array();
    $receiveddone = false;
    while (true) {
    // Read the first byte of input which gives us some or all of the length
    // of the remaining reply.
    $BYTE = ord(fread($this->socket, 1));
    $LENGTH = 0;
    // If the first bit is set then we need to remove the first four bits, shift left 8
    // and then read another byte in.
    // We repeat this for the second and third bits.
    // If the fourth bit is set, we need to remove anything left in the first byte
    // and then read in yet another byte.
    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;
    }
    // If we have got more characters to read, read them in.
    if ($LENGTH > 0) {
    $_ = "";
    $retlen = 0;
    while ($retlen < $LENGTH) {
    $toread = $LENGTH - $retlen;
    $_ .= fread($this->socket, $toread);
    $retlen = strlen($_);
    }
    $RESPONSE[] = $_;
    $this->debug('>>> [' . $retlen . '/' . $LENGTH . '] bytes read.');
    }
    // If we get a !done, make a note of it.
    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;
    }


    /**
    * Write (send) data to Router OS
    *
    * @param string $command A string with the command to send
    * @param mixed $param2 If we set an integer, the command will send this data as a "tag"
    * If we set it to boolean true, the funcion will send the comand and finish
    * If we set it to boolean false, the funcion will send the comand and wait for next command
    * Default: true
    *
    * @return boolean Return false if no command especified
    */
    function write($command, $param2 = true)
    {
    if ($command) {
    $data = explode("\n", $command);
    foreach ($data as $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) : ''));
    return true;
    } else
    return false;
    }


    /**
    * Write (send) data to Router OS
    *
    * @param string $com A string with the command to send
    * @param array $arr An array with arguments or queries
    *
    * @return array Array with parsed
    */
    function comm($com, $arr = array())
    {
    $count = count($arr);
    $this->write($com, !$arr);
    $i = 0;
    foreach ($arr as $k => $v) {
    switch ($k[0]) {
    case "?":
    $el = "$k=$v";
    break;
    case "~":
    $el = "$k~$v";
    break;
    default:
    $el = "=$k=$v";
    break;
    }
    $last = ($i++ == $count - 1);
    $this->write($el, $last);
    }
    return $this->read();
    }
    }
    ?>
    Segue um exemplo do novo arquivo

    <?php
    require('routeros_api.class.php');


    $API = new routeros_api();


    $API->debug = false;


    if ($API->connect('enderecodoservidor', 'usuario', 'senha')) {


    $API->write('/interface/getall');


    $READ = $API->read(false);
    $ARRAY = $API->parse_response($READ);


    print_r($ARRAY);
    /*foreach($ARRAY as $ARRAYS){
    echo "Nome: ".$ARRAYS['name']."<br>";
    echo "IP: ".$ARRAYS['target-addresses']."<br>";
    }*/


    $API->disconnect();


    }
    ?>
    Mais detalhado que isso só se fizer o trabalho todo.

  11. #11

    Padrão Re: Mikrotik API !

    Citação Postado originalmente por shuttner Ver Post
    Não sei onde pessoal ta achando difícil.
    No caso do PHP, vocês tem que salvar a classe routeros_api num arquivo php (coisa extremamente difícil que não estão entendendo, então fica a dica da mágica), de preferência coloque o arquivo da classe de conexão no mesmo local onde você vai criar o outro arquivo a ser criado.



    Segue um exemplo do novo arquivo



    Mais detalhado que isso só se fizer o trabalho todo.
    uma pergunta isso ai e 2 arquivos php? jogo eles no DW por exemplo salvo o primeiro como cadastro.php e o segundo com registre-se.phg por exemplo seria isso? ativo o API e jogos estes dois arquivos dentro de file e crio um atalho no hotspot é isso? to meio voado e nisso.

  12. #12
    Avatar de shuttner
    Ingresso
    Aug 2008
    Localização
    Boa Vista - Roraima
    Posts
    257
    Posts de Blog
    1

    Padrão Re: Mikrotik API !

    Fiz um vídeo rápido mostrando um exemplo, mais mastigado que isso não da.
    http://www.nortetrack.com.br/apimk.zip

  13. #13

    Padrão Re: Mikrotik API !

    Citação Postado originalmente por shuttner Ver Post
    Fiz um vídeo rápido mostrando um exemplo, mais mastigado que isso não da.
    http://www.nortetrack.com.br/apimk.zip
    obrigado vou dar uma olhada.

  14. #14

    Padrão Re: Mikrotik API !

    eu vi como salvar ele em php como vc fez o vídeo ai que vc mostrou Shuttner eu gostaria de saber como colocar pra funcionar como adequa a minha rede só quero que o cliente se cadastre e já navegue pode ser com apenas uma senha padrão até eu receber o email e confirmar pra ele depois algo do tipo.
    desde já agradeço.

  15. #15
    Avatar de shuttner
    Ingresso
    Aug 2008
    Localização
    Boa Vista - Roraima
    Posts
    257
    Posts de Blog
    1

    Padrão Re: Mikrotik API !

    Agora é você quem vai fazer.

  16. #16

    Padrão Re: Mikrotik API !

    certo mais eu não sei onde colocar estes arquivos eu tenho que colocar eles em file e criar uma atalho na pagina do hostpot? ou como sera feito?

  17. #17
    Avatar de shuttner
    Ingresso
    Aug 2008
    Localização
    Boa Vista - Roraima
    Posts
    257
    Posts de Blog
    1

    Padrão Re: Mikrotik API !

    coloque num servidor separado, pode ser windows, linux
    e um atalho no seu hotspot.

  18. #18

    Padrão Re: Mikrotik API !

    certo, e que programa eu devo utilizar pra puxar estes arquivos dele e depois que o cliente se cadastrar mandar de volta para o mikrotik?

  19. #19
    Avatar de shuttner
    Ingresso
    Aug 2008
    Localização
    Boa Vista - Roraima
    Posts
    257
    Posts de Blog
    1

    Padrão Re: Mikrotik API !

    puxar que arquivo cara?
    vc só tem que configura um servidor http na sua rede colocar o seu projeto nele e criar um atalho no seu hotspot.
    Vc vai executar comandos direto no mk.

  20. #20

    Padrão Re: Mikrotik API !

    ok! obrigado farei isso obrigado.