Giter VIP home page Giter VIP logo

aluisiora / routeros-client Goto Github PK

View Code? Open in Web Editor NEW
71.0 5.0 31.0 442 KB

Abstraction layer over the node-routeros API

License: MIT License

TypeScript 56.81% JavaScript 43.16% Shell 0.03%
mikrotik mikrotik-api routerboard routerboard-api routeros routeros-api javascript typescript nodejs node routeros-node api mikrotik-routerboard-api promise node-routeros wrapper mikrotik-wrapper routeros-wrapper routerboard-wrapper

routeros-client'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.

RouterOS Client

This is a client wrapper for node-routeros api for doing common tasks and making the api easier to use for small and large NodeJS projects.

Getting Started

These instructions will help you install and use some of the client features, you can get a complete documentation in the wiki.

Prerequisites

You must be familiar with Promises, how to chain it, how to catch errors and etc.

Installing

You can install by using npm:

npm install routeros-client --save

Note: you are not required to install node-routeros since it's already a dependency of this lib.

Features

Everything you get from the node-routeros is still here, plus:

  • You can save the menu and reuse it for multiple operations.
  • There is a "Model" feature where you can fire commands on each entry of a menu individually (check the examples).
  • Easy to read and write reusable code.

Examples

Here are some short examples of usage, head to the wiki for a complete documentation.

Connecting

const RouterOSClient = require('routeros-client').RouterOSClient;

const api = new RouterOSClient({
    host: "192.168.88.1",
    user: "admin",
    password: "123456"
});

api.connect().then((client) => {
    // After connecting, the promise will return a client class so you can start using it

    // You can either use spaces like the winbox terminal or
    // use the way the api does like "/system/identity", either way is fine
    client.menu("/system identity").getOnly().then((result) => {
        console.log(result.identity); // Mikrotik
        api.close();
    }).catch((err) => {
        console.log(err); // Some error trying to get the identity
    });

}).catch((err) => {
    // Connection error
});

Printing only VLAN interfaces

api.connect().then((client) => {

    client.menu("/interface").where("type", "vlan").get().then((results) => {
        // results is an array of all the vlan interfaces
    }).catch((err) => {
        // error getting interfaces
    });

}).catch((err) => {
    // Connection error
});

Adding and editing a firewall rule

api.connect().then((client) => {

    const filterMenu = client.menu("/ip firewall filter");

    filterMenu.add({
        chain: "forward",
        action: "accept",
        protocol: "tcp",
        dstPort: 80
    }).then((response) => {
        // response should be an object like { ret: "*3C" }
        return filterMenu.where("id", response.ret).update({
            srcAddress: "192.168.88.5"
        });

    }).then((response) => {
        // response should be an empty array [] since, 
        // if there is no error, updates return nothing, meaning success
        api.close();
    }).catch((err) => {
        // error adding or eiditing
    });

}).catch((err) => {
    // Connection error
});

Using the Model

api.connect().then((client) => {

    client.menu("/ip proxy access").getModel().then((results) => {

        // Suppose we want to disable acl #2 on the access list
        results[2].disable(); // this returns a Promise too

        // If we want to remove acl #5
        results[5].remove().then(() => {
            // removed successfully
        }, (err) => {
            // error trying to remove
        });

        // Or if we want to update acl #0
        results[0].update({
            comment: "Updated through Model"
        }).then((result) => {
            // result is the updated version
        }).catch((err) => {
            // error updating
        });

    }).catch((err) => {
        // error getting proxy access list
    });

}).catch((err) => {
    // Connection error
});

Creating a model from an item

api.connect().then((client) => {

    client.menu("/interface").where({ interface: "ether1"}).getOnly().then((result) => {

        const ether1 = client.model(result);

        ether1.update({
            comment: "WAN"
        }).then((updatedEther1) => {
            // Should return an updated version of the ether1,
            // but since it is the same object...
            console.log(ether1 === updatedEther1); // true

            console.log(ether1.comment); // WAN
        }).catch((err) => {
            // error updating
        });

    }).catch((err) => {
        // error getting proxy access list
    });

}).catch((err) => {
    // Connection error
});

Streaming content

api.connect().then((client) => {

    // The stream function returns a Stream object
    // so you are able to pause, resume or stop
    const torch = client.menu("/tool torch")
        .where({interface: "ether1"})
        .stream((err, data, stream) => {
            if (err) return err; // got an error while trying to stream

            console.log(data); // the data from the stream itself

            // Will start the countdown after the 
            // first stream of data is received
            stopTorching(); 
        });

    // Variable to store the timeout
    let finalCountdown;
    const stopTorching = function(){
        // If the timeout wasn't set yet
        if (!finalCountdown) {
            // Start counting 5 seconds to stop the stream
            finalCountdown = setTimeout(() => {
                torch.stop();
            }, 5000);
        }
    };

}).catch((err) => {
    // Connection error
});

Cloning this repo

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

Running the tests

There aren't that many tests, but in order to run them, I used RouterOS CHR (look for the Cloud Hosted Router if you aren't familiar with it yet) on a virtual machine with 4 interfaces, where the first interface is a bridge of my network card:

VirtualBox RouterOS CHR Conf

Also, the vm gets the 10.62.0.25 ip address, you might want to change that in the test files according to network. The user and password was set to admin and admin respectively.

Run the tests using:

npm test

The testing was created using mocha and chai.

TODO

  • Write more tests

License

MIT License

Copyright (c) 2017 Aluisio 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.

routeros-client's People

Contributors

aluisiora avatar aluisiosip avatar haakonnessjoen 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

Watchers

 avatar  avatar  avatar  avatar  avatar

routeros-client's Issues

Cannot connect through VPN

Code

const RouterOSClient = require('routeros-client').RouterOSClient;

const api = new RouterOSClient({
  host: 'https://************:12',
  user: '*****',
  password: '********',
});

api
  .connect()
  .then(async (client) => {
    // Connection successful
    console.log('Connection Successful');

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

Error

$ node index.js
RosException
    at Connector.onError (E:\Projects\mikrotek-test\node_modules\node-routeros\dist\connector\Connector.js:176:15)
    at Socket.emit (events.js:210:5)
    at emitErrorNT (internal/streams/destroy.js:92:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  name: 'RosException',
  errno: 'ENOTFOUND'
}

speed-test stream

Hi guys looking to use the speed-test tool in the API

I get it to work just fine and returns a array of all the sections of the test but what i would like is to actuality be able to stream the test instead of waiting for the array of elements is this possible

This is the code i have sofar and like i say it works but ideally i need to open a stream

api.connect().then((client) => { cont test = client .menu("/tool") .exec("speed-test", { user: "user", password: "pass", address: "someip", }) .then((result) => { console.log(result); }); });

RosException

Hi,
I use this package with node.js using socket.io to communicate with server. I received data perfectly, but after a few seconds my app stoped and show me error.
RosException
at Connector.onError (……/node_modules/node-routeros/dist/connector/Connector.js:169:15)
at Socket.emit (events.js:321:20)
at emitErrorNT (internal/streams/destroy.js:84:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
name: 'RosException',
errno: -104
}

getting an exception while deleting a record

So, I've created a record:

/ip hotspot user add server all name user1 password 123456789 profile default

then I'm trying to delete it:

api.connect().then((client) => {
    client.menu("/ip hotspot user").where("name", "user1").remove().then((response) => {
        console.log(response);// response is an array of all items removed
    }).catch((err) => {
        // Error getting the list of firewall filter entries
        console.log(err);
    });
});

{
'$$path': '/ip/hotspot/user',
id: '*B',
name: 'user1',
password: 123456789,
profile: 'default',
uptime: '0s',
bytesIn: 0,
bytesOut: 0,
packetsIn: 0,
packetsOut: 0,
dynamic: false,
disabled: false
}
Response: true
events.js:292
throw er; // Unhandled 'error' event
^
RosException: Timed out after 10 seconds
at Connector.onTimeout (C:\Users\user\Desktop\temp\node_modules\node-routeros\dist\connector\Connector.js:187:30)
at Object.onceWrapper (events.js:421:28)
at Socket.emit (events.js:315:20)
at Socket._onTimeout (net.js:482:8)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
Emitted 'error' event on RouterOSClient instance at:
at RouterOSAPI. (C:\Users\user\Desktop\temp\node_modules\routeros-client\dist\RouterOSClient.js:34:53)
at Object.onceWrapper (events.js:422:26)
at RouterOSAPI.emit (events.js:315:20)
at Connector.connectedErrorListener (C:\Users\user\Desktop\temp\node_modules\node-routeros\dist\RouterOSAPI.js:105:30)
at Object.onceWrapper (events.js:422:26)
at Connector.emit (events.js:315:20)
at Connector.onTimeout (C:\Users\user\Desktop\develop\temp\node_modules\node-routeros\dist\connector\Connector.js:187:14)
at Object.onceWrapper (events.js:421:28)
at Socket.emit (events.js:315:20)
at Socket._onTimeout (net.js:482:8) {
errno: 'SOCKTMOUT'
}

a log records in routerOS:
00:00:00 system,info hotspot user user1 removed by admin
00:00:00 system,info,account user admin logged out from 192.168.1.254 via api

Thank you for the routerOS client! Well done! It's just what the doctor ordered! :D

problem on torch pppoe interface

Hi, i trying torch pppoe interface but does not work

const RouterOSClient = require("routeros-client").RouterOSClient;

const routeros = new RouterOSClient({

    host: process.env.SERVER_HOST,
    user: process.env.SERVER_USER,
    password: process.env.SERVER_PASSWORD,
});

routeros
  .connect()
  .then((client) => {
    const torchMenu = client.menu("/ppp torch")
    .where({interface: "<pppoe-test_client>"})
    .stream((err, data) => {
    if (err) console.log(err)
    console.log(data)
    })

  })
  .catch((err) => {
    console.log("Error: ", err);
  });

Request: an add time function for some timer parameters

This is something i was trying to handle with some regex extracting the values that the API returns and add the time i want for example:

let's say that i have a user in the hotspot which returns the value

limitUptime='1d12h'

but if i want to increase that limit with something like limitUptime + "1h" isn't possible without lots of manually regex, split and join methods for that string, so a helper function for this would be a realive.

Error with TypeScript 2.9.2

Compilation error with TypeScript 2.9.2:

node_modules/routeros-client/dist/RosApiModel.d.ts:35:5 - error TS2416: Property 'move' in type 'RosApiModel' is not assignable to the same property in base type 'RouterOSAPICrud'.
  Type '(to?: string | number | undefined) => Promise<any>' is not assignable to type '(from: Id, to?: string | number | undefined) => Promise<any>'.
    Types of parameters 'to' and 'from' are incompatible.
      Type 'Id' is not assignable to type 'string | number | undefined'.
        Type '(string | number)[]' is not assignable to type 'string | number | undefined'.
          Type '(string | number)[]' is not assignable to type 'number'.

35     move(to?: string | number): Types.SocPromise;
       ~~~~

My dependencies in package.json are:

  "devDependencies": {
    "@types/node": "^10.5.1",
    "@types/serialize-error": "^2.1.0",
    "rimraf": "^2.6.2",
    "typescript": "^2.9.2"
  },
  "dependencies": {
    "influx": "^5.0.7",
    "routeros-client": "^0.10.1",
    "serialize-error": "^2.1.0"
  }

Other than the above, the package is working fine.

cant get /interface/wireless/monitor Information

Hi This is more a question than an issue

I need to pull the interface CCQ I use to do this via php_api but now a use node
so id like to move away from the PHP if I can

Is it at all possible to get the information from

menu('/interface/wireless/monitor') or something in that line allmost :-)

I try doing this using node-routeros as well can't seem to be able to get it there is either

Where Filter Not Working With Update, Delete, Remove.

When using this library with the where filter to do updates, remove, delete there is a bug that just returns some random result from that menu if the where the filter is not true.
I now have to use get on any resource before invoking update, remove or delete

I cant add user to radius server via /tool/user-manage/add anyone can help me

Im trying create a new user with this code but doesnt work

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

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

const data ={
    username:'test',
    password:'testt',
    customer:'ADMIN'

}
conn.connect()
    .then(() => {
        const d = [
			'=name='+data.username,
	    	'=password='+data.password,
	    	'=customer='+data.customer,
		];
        conn.write('tool/user-manage/user/add', d )
            .then((data) => {
                console.log('OK');
            })
            .catch((err) =>{
                  console.log('Error')
            })
    })
    .catch((err) => {
        // Got an error while trying to connect
        console.log(err);
    });```

Stream does not work

Hi, I wrote this code to get Tx-Packets and Rx-Packets.

const RouterOSClient = require('routeros-client').RouterOSClient
const api = new RouterOSClient({
host: process.env.SERVER_HOST,
user: process.env.SERVER_USER,
password: process.env.SERVER_PASSWORD,
keepalive: true
})

api.connect().then(client => {
const torchMenu = client.menu("/tool torch")
.where({interface: "WAN-1"})
.stream((err, data) => {
if (err) console.log(err)
console.log(data)
})
})

This code shows error:
TypeError: this.debounceSendingEmptyData is not a function.

Could you please help me to solve this issue.

improve remove, update and etc to query for the id of the entry

Expand methods like update, remove, unset and etc to accept a where query and use that to retrieve the entries ids to run the commands. Goal is to achieve something like this:

addressMenu
.where("address", "192.168.88.15/24")
.orWhere("address", "192.168.15.88/24")
.remove();

events.js:167 throw er; // Unhandled 'error' event

Hi,

I get this weird unhandled 'error' event and node server just crash.
Is this node or routeros-client related?

"node": "v10.4.1"
"routeros-client": "^0.11.0"

events.js:167
throw er; // Unhandled 'error' event
^
RosException: Timed out after 10 seconds
at Connector.onTimeout (/var/app/node_modules/node-routeros/dist/connector/Connector.js:181:30)
at Object.onceWrapper (events.js:273:13)
at Socket.emit (events.js:182:13)
at Socket._onTimeout (net.js:444:8)
at ontimeout (timers.js:427:11)
at tryOnTimeout (timers.js:289:5)
at listOnTimeout (timers.js:252:5)
at Timer.processTimers (timers.js:212:10)
Emitted 'error' event at:
at RouterOSAPI.rosApi.once (/var/app/node_modules/routeros-client/dist/RouterOSClient.js:33:53)
at Object.onceWrapper (events.js:273:13)
at RouterOSAPI.emit (events.js:182:13)
at Connector.connectedErrorListener (/var/app/node_modules/node-routeros/dist/RouterOSAPI.js:103:30)
at Object.onceWrapper (events.js:273:13)
at Connector.emit (events.js:182:13)
at Connector.onTimeout (/var/app/node_modules/node-routeros/dist/connector/Connector.js:181:14)
at Object.onceWrapper (events.js:273:13)
at Socket.emit (events.js:182:13)
at Socket._onTimeout (net.js:444:8)

Thanks for help!

Switching between servers.

I have this code to get information from server. But when I switch to the second server still first server remain active and (TotalClients) code bring me data for both servers (one time for the first server and another time for the second server) in each 5 seconds. How I can stop reading from one server and listing just for second server.
`
const RouterOSClient = require('routeros-client').RouterOSClient
let api

serverConnection = (data) => {
return new RouterOSClient({
host: data.host,
user: data.user,
password: data.password,
keepalive: true,
timeout: 50
})
}

socket.on('TotalClients', (serverData, status) => {
if(status == true) {
api = serverConnection(serverData)
api.connect().then(client => {
client.menu("/ppp secret")
.query({ interval: 5 })
.stream('print', (err, data) => {
if(data.length > 0) io.emit('Clients-Length', data.length)
})
})
} else {
if(api) {
const closing = api.rosApi.closing
if(!closing) api.close()
}
}
})
})
`

TypeError: RouterOSClient is not a constructor

i was tying to use this package with create-react-app with typescript, at the time of compilation everything goes right, but when i try to use, lets say this simple login function

import { IRosOptions, RouterOSClient } from 'routeros-client';

const login = async (cred: IRosOptions) => {
  const api = new RouterOSClient({ ...cred });
  try {
    const conn = await api.connect();
    if (api.isConnected()) api.disconnect();
    return true;
  } catch (error) {
    throw error;
  }
};

i got this error:

TypeError: net_1.Socket is not a constructor
    at Connector.connect (Connector.js:85)
    at RouterOSAPI.js:137
    at new Promise (<anonymous>)
    at RouterOSAPI.connect (RouterOSAPI.js:100)
    at RouterOSClient.connect (RouterOSClient.js:41)
    at login (MikrotikAPI.ts:19)
    at Login.handleLogin (Login.tsx:55)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
    at invokeGuardedCallback (react-dom.development.js:250)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:265)
    at executeDispatch (react-dom.development.js:571)
    at executeDispatchesInOrder (react-dom.development.js:596)
    at executeDispatchesAndRelease (react-dom.development.js:695)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:704)
    at forEachAccumulated (react-dom.development.js:676)
    at runEventsInBatch (react-dom.development.js:844)
    at runExtractedEventsInBatch (react-dom.development.js:852)
    at handleTopLevel (react-dom.development.js:5029)
    at batchedUpdates$1 (react-dom.development.js:21463)
    at batchedUpdates (react-dom.development.js:2247)
    at dispatchEvent (react-dom.development.js:5109)
    at react-dom.development.js:21520
    at Object.unstable_runWithPriority (scheduler.development.js:255)
    at interactiveUpdates$1 (react-dom.development.js:21519)
    at interactiveUpdates (react-dom.development.js:2268)
    at dispatchInteractiveEvent (react-dom.development.js:5085)

even if i change the syntax to old require as in the examples like this

import { IRosOptions } from 'routeros-client';

const { RouterOSClient } = require('routeros-client').RouterOSClient;

const login = async (cred: IRosOptions) => {
  const api = new RouterOSClient({ ...cred });
  try {
    const conn = await api.connect();
    if (api.isConnected()) api.disconnect();
    return true;
  } catch (error) {
    throw error;
  }
};

i got this error

TypeError: RouterOSClient is not a constructor
    at login (MikrotikAPI.ts:6)
    at Login.handleLogin (Login.tsx:55)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
    at invokeGuardedCallback (react-dom.development.js:250)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:265)
    at executeDispatch (react-dom.development.js:571)
    at executeDispatchesInOrder (react-dom.development.js:596)
    at executeDispatchesAndRelease (react-dom.development.js:695)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:704)
    at forEachAccumulated (react-dom.development.js:676)
    at runEventsInBatch (react-dom.development.js:844)
    at runExtractedEventsInBatch (react-dom.development.js:852)
    at handleTopLevel (react-dom.development.js:5029)
    at batchedUpdates$1 (react-dom.development.js:21463)
    at batchedUpdates (react-dom.development.js:2247)
    at dispatchEvent (react-dom.development.js:5109)
    at react-dom.development.js:21520
    at Object.unstable_runWithPriority (scheduler.development.js:255)
    at interactiveUpdates$1 (react-dom.development.js:21519)
    at interactiveUpdates (react-dom.development.js:2268)
    at dispatchInteractiveEvent (react-dom.development.js:5085)


im trying to make this work with React and typescript

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.