Giter Site home page Giter Site logo

node-routeros's Introduction

Discontinued

I worked on this project in my spare time, but unfortunately I no longer work with mikrotik devices and don't have the free time anymore, so consider it as discontinued. Feel free to fork this project and create your own spin.

Description

This is a Mikrotik Routerboard API written in Typescript for nodejs, can be either used with plain javascript or imported on typescript projects.

This library will handle the API in a more lowerlevel way, for a simpler to use interface I recommend my routeros-client for a more "object-oriented" API, which wraps this API. It has a very rich documentation, so please check it out.

Features

  • Connection and reconnection without destroying the object.
  • Change host, username and other parameters of the object without recreating it.
  • Based on promises.
  • You can choose to keep the connection alive if it gets idle.
  • Every command is async, but can be synced using the promises features.
  • Can pause, resume and stop streams (like what you get from /tool/torch).
  • Support languages with accents, keeping it consistent throughout winbox and api.

Installing

npm install node-routeros --save

Documentation

Check the wiki for a complete documentation.

Examples

You can import in TypeScript using:

import { RouterOSAPI } from 'node-routeros';

Adding an IP address to ether2, printing it, then removing it synchronously:

const RosApi = require('node-routeros').RouterOSAPI;

const conn = new RosApi({
    host: '192.168.88.1',
    user: 'admin',
    password: '',
});

conn.connect()
    .then(() => {
        // Connection successful

        // Let's add an IP address to ether2
        conn.write('/ip/address/add', [
            '=interface=ether2',
            '=address=192.168.90.1',
        ])
            .then((data) => {
                console.log('192.168.90.1 added to ether2!', data);

                // Added the ip address, let's print it
                return conn.write('/ip/address/print', ['?.id=' + data[0].ret]);
            })
            .then((data) => {
                console.log('Printing address info: ', data);

                // We got the address added, let's clean it up
                return conn.write('/ip/address/remove', [
                    '=.id=' + data[0]['.id'],
                ]);
            })
            .then((data) => {
                console.log('192.168.90.1 as removed from ether2!', data);

                // The address was removed! We are done, let's close the connection
                conn.close();
            })
            .catch((err) => {
                // Oops, got an error
                console.log(err);
            });
    })
    .catch((err) => {
        // Got an error while trying to connect
        console.log(err);
    });

Listening data from /ip/torch and using pause/resume/stop feature:

const RosApi = require("node-routeros").RouterOSAPI;

const conn = new RosApi({
    host: "192.168.88.1",
    user: "admin"
    password: ""
});

conn.connect().then(() => {
    // Counter to trigger pause/resume/stop
    let i = 0;

    // The stream function returns a Stream object which can be used to pause/resume/stop the stream
    const addressStream = conn.stream(['/tool/torch', '=interface=ether1'], (error, packet) => {
        // If there is any error, the stream stops immediately
        if (!error) {
            console.log(packet);

            // Increment the counter
            i++;

            // if the counter hits 30, we stop the stream
            if (i === 30) {

                // Stopping the stream will return a promise
                addressStream.stop().then(() => {
                    console.log('should stop');
                    // Once stopped, you can't start it again
                    conn.close();
                }).catch((err) => {
                    console.log(err);
                });

            } else if (i % 5 === 0) {

                // If the counter is multiple of 5, we will pause it
                addressStream.pause().then(() => {
                    console.log('should be paused');

                    // And after it is paused, we resume after 3 seconds
                    setTimeout(() => {
                        addressStream.resume().then(() => {
                            console.log('should resume');
                        }).catch((err) => {
                            console.log(err);
                        });
                    }, 3000);

                }).catch((err) => {
                    console.log(err);
                });

            }

        }else{
            console.log(error);
        }
    });

}).catch((err) => {
    // Got an error while trying to connect
    console.log(err);
});

Cloning this repo

Note that, if are cloning this repo, you must be familiar with Typescript so you can make your changes.

Testing

In order to run the tests, I used RouterOS CHR on a virtual machine with 4 interfaces, where the first interface is a bridge of my network card:

VirtualBox RouterOS CHR Conf

TODO

  • Write more tests

Credits

This project is entirely based on George Joseph and Brandon Myers's work with mikronode, thank you very much!!!

License

MIT License

Copyright (c) 2017 Aluísio Rodrigues Amaral

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

node-routeros's People

Contributors

aluisiora avatar aluisiosip avatar cenuij avatar danlobo avatar excelnet-public avatar khandieyea avatar qbitz avatar zackmattor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-routeros's Issues

How to detect RouterOSAPI.stream's end

How to detect when a RouterOSAPI.stream is complete?

I'm testing using the /ip/address/print command.
I was expecting the stream returned from RouterOSAPI.stream to emit either the close or the end event, but neither one is emitted.

Timed out after 10 seconds

I tested on my Mikrotik (just connecting):

{
name: "RosException",
errno: "SOCKTMOUT",
message: "Timed out after 10 seconds"
}

I applied to port 8728 but still, it doesn't work.

TypeScript's d.ts files are missing

node-routeros does not provide TypeScript's d.ts files starting with version 1.4.4.
I tried installing them from the package @types/node-routeros, but that doesn't exist.
Where may I find the TypeScript's d.ts files now?

Make the TLS feature work

Currently, connecting with SSL via api is not very well tested, need to write tests and make fixes if needed.

Wrong sentence processing when printing

Occasionally, the api assign the wrong stack of data of the tag sentences received, making the index of the response being assign to 1, while the index 0 being a wrong sentence that should be part of the last packet processed.

This problem breaks when trying to print data, but it doesn't manifest very often.

Getting Log Records by Topic Name

Hello. Thanks for the useful Library. How can I get Log Records by Topic Name, like by this RouterOS Command: log print where topics~"warning" ?
Of course, I can fetch all Records and then filter by JS Array Methods, but how can I it rich with Command Parameters?

Connection error leaving command promises orphaned

We have a few bad actors in our fleet of routers. We get periodic TCP connection resets from them which cause the connection to throw an error. When this happens any inflight API calls get orphaned - never to resolve or reject. Goofy example is as follows.

routeros.on('error', (e) => logger(e));

function doThings() {
  let res = await routeros.write('/systen/resource/print');
  console.log(res.data);
  setTimeout(doThings, 5000);
}

doThings();
  1. doThings gets called
  2. /system/resource/print gets sent to router
  3. Router sends back response
  4. data gets logged
  5. doThings gets schedules for 5 seconds down the road
  6. doThings gets called
  7. /system/resource/print gets sent to router
  8. ECONNRESET gets thrown
  9. error gets logged
  10. promise never gets resolved which means we are waiting forever for /system/resource/print and we never proceed

Actual scenario is a bit more complex than this.... but I think this outlines the issue. Currently we have a workaround. But my suggestion would be for all inflight writes to reject their promises upon connection error.

No data when torch sends empty info

During torch interval, if there is nothing to be displayed, nothing is received from the tcp socket. This might end in a timeout if keepalive is set to false.

  • Deal with empty data interval.

remove by id doesn't work

Hi! I can delete anything.
I got empty array [] as response for deleting actions without any error

RosException CANTLOGIN Username or password is invalid

RouterOS v6.45.9

Tried this code and says cannot login.

const RosApi = require('node-routeros').RouterOSAPI;

const conn = new RosApi({
  host: '*******',
  user: '******',
  password: '******',
});

conn
  .connect()
  .then(() => {
    // Connection successful
    console.log('Connection Successful')
  })
  .catch((err) => {
    // Got an error while trying to connect
    console.log(err);
  });

Error

RosException: Username or password is invalid
    at E:\Projects\mikrotek-test\node_modules\node-routeros\dist\RouterOSAPI.js:397:23
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  name: 'RosException',
  errno: 'CANTLOGIN',
  message: 'Username or password is invalid'
}

RosException - https://github.com/aluisiora/routeros-client/issues/8

Hi,

I'm using routeros-client

#Ref issue

Could you please look into this @aluisiora

Error: RosException: Timed out after 10 seconds
at RosException (..../node_modules/node-routeros/dist/RosException.js:11:14)
at onTimeout (..../node_modules/node-routeros/dist/connector/Connector.js:180:33)
at onceWrapper (events.js:277:12)
at emit (events.js:189:12)
at EventEmitter.emit (domain.js:459:22)
at Socket._onTimeout (net.js:440:7)
at ontimeout (timers.js:436:10)
at tryOnTimeout (timers.js:300:4)
at listOnTimeout (timers.js:263:4)
at processTimers (timers.js:223:9)

Help to create a ping streaming script

I am currently writing a Telegram bot that can do the ping command (among other things) and I would like to hear if anyone can help with an example. So basically if ping count is not specified, make it 4 and ping to host at IP xxxx. If it possible to perhaps save the data after the run into min, average and max.
Thank you for the help

Stream data to object

Hi

Been using the stream function to get tx and rx speeds of interfaces however seems like the packets i get back from the stream is not in JSON or OBJECT type what would be the best way to parse this so i can use it in my program

what i get back is below and for some odd reason when i try and parse it i get a error
might be me being dumb but assistance would be much appreciated

happy to share rest of my code if needed but is just a simple stream function :-)

tried running both

JSON.parse(packet);
JSON.parse(...packet);

error i get is
SyntaxError: Unexpected token o in JSON at position 1

[
{
name: 'wlan1',
'rx-packets-per-second': '3',
'rx-bits-per-second': '2016',
'fp-rx-packets-per-second': '3',
'fp-rx-bits-per-second': '2016',
'rx-drops-per-second': '0',
'rx-errors-per-second': '0',
'tx-packets-per-second': '5',
'tx-bits-per-second': '8880',
'fp-tx-packets-per-second': '3',
'fp-tx-bits-per-second': '3144',
'tx-drops-per-second': '0',
'tx-queue-drops-per-second': '0',
'tx-errors-per-second': '0',
'.section': '0'
}
]
[
{
name: 'wlan1',
'rx-packets-per-second': '4',
'rx-bits-per-second': '2752',
'fp-rx-packets-per-second': '4',
'fp-rx-bits-per-second': '2752',
'rx-drops-per-second': '0',
'rx-errors-per-second': '0',
'tx-packets-per-second': '6',
'tx-bits-per-second': '10016',
'fp-tx-packets-per-second': '3',
'fp-tx-bits-per-second': '3184',
'tx-drops-per-second': '0',
'tx-queue-drops-per-second': '0',
'tx-errors-per-second': '0',
'.section': '1'
}
]

failure to send parameters

I can not send this command /ppp secret print count-only where name =" username "

I use:
conn.write("/ppp/secret/print",[ "=count-only where name=username" ....

Could you help me?

Many thanks

Ocasionally throws UNKNOWNREPLY

Hard to reproduce.
Sometimes, when dealing with huge amount of received data, a UNKNOWNREPLY is thrown.
Still investigating.

processRawData bug...

Howdy! We are using the newest release of this library. It seems like we are hitting some stream parsing issue. We were using the Mikronode library previously and we needed to fix a bug regarding the sentance length parsing and I wonder if this is somehow related?

violetatrium/mikronode@10467e3

 TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type object
     at Function.from (buffer.js:305:9)
     at Receiver.processRawData (/usr/src/app/node_modules/node-routeros/dist/connector/Receiver.js:136:65)
     at Connector.onData (/usr/src/app/node_modules/node-routeros/dist/connector/Connector.js:192:23)
     at Socket.emit (events.js:223:5)
     at Socket.EventEmitter.emit (domain.js:475:20)
     at Shim.applySegment (/usr/src/app/node_modules/newrelic/lib/shim/shim.js:1424:20)
     at Socket.wrapper [as emit] (/usr/src/app/node_modules/newrelic/lib/shim/shim.js:2065:17)
     at addChunk (_stream_readable.js:309:12)
     at readableAddChunk (_stream_readable.js:290:11)
     at Socket.Readable.push (_stream_readable.js:224:10)

Documentation

Hello.
Is there somewhere in the public access info how to prepare configs for multiple connections(lists with hosts, passwords, etc.)?

App Crashed with Timed out after 10 seconds'

Hello I have a problem with adding a queue.

If I add a queue record that already has a name, mikrotik rejects this request, of course.

The problem is that my node-routeros server crashes with the following error.
"failure: already have such name"

name: 'RosException',
errno: 'SOCKTMOUT',
message: 'Timed out after 10 seconds'

Is it possible to just get the error message and the server doesn't shut down?

Code BackEnd.
Server js

Error App Crash
Error

Is this possible?

How do I execute this command?

[admin@MikroTik] interface pppoe-server> remove [find user=ex]

I have tried in several ways, example:

const response = await conn.write(["/interface/pppoe-server/remove", "?[find user=ex]"]);

No error happens, and the return is an empty array!

Help me please?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.