NodeJS Mikrotik API 最小示例
这是使用 NodeJS 和 mikrotik 包 访问 Mikrotik API 的示例。
首先,安装包
install_mikrotik_package.sh
npm i --save mikrotik此外,为了启用 import 语句,设置
package.json
"type": "module"在 package.json 中。
示例代码:
mikrotik_example.mjs
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));
});例如,这将输出:
addresses_output.txt
Address: 192.168.88.1/24 on bridge
Address: 10.1.2.3/24 on bridge如果用户名/密码凭据错误,它将打印:
error_output.txt
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}}If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow