NodeJS Mikrotik API minimal example
This is an example of access the Mikrotik API using NodeJS and the mikrotik
package.
First, install the package
npm i --save mikrotik
Also, in order to enable import
statement, set
"type": "module"
in package.json
.
Example code:
import * as MikroNode from 'mikrotik' ;
const host = "10.56.23.4";
const username = "admin";
const password = "N@CdVTz8y@D$KwVS5TTo"; // Hope that's not your real password ;)
const connection = MikroNode.getConnection(host, username, password, {
closeOnDone : true
});
connection.getConnectPromise().then(function(conn) {
conn.getCommandPromise('/ip/address/print').then(addresses => {
for(const address of addresses) {
console.info(`Address: ${address.address} on ${address.interface}`);
}
}, reason => {
console.log('Error while running command: ' + JSON.stringify(reason));
});
}).catch(reason => {
console.log('Error while connecting: ' + JSON.stringify(reason));
});
This will output, for example:
Address: 192.168.88.1/24 on bridge
Address: 10.1.2.3/24 on bridge
In case of bad username/password credentials, it will print:
Error while connecting: {"errors":[{"category":"","message":"invalid user name or password (6)"}],"channelId":"login","channel":{"id":"login","running":true,"closing":true,"closed":true,"clearEvents":false,"saveBuffer":true,"closeOnDone":false,"lastCommand":["/login","=name=admin","=password=admin1234",".tag=login"],"_events":{},"_eventsCount":0}}