MikroTik

How to access RouterOS API in Python using the ‘routeros’ library (minimal example)

This example uses the routeros library from PyPI (GitHub) to access the MikroTik API and extract the system identity.

#!/usr/bin/env python3
from routeros import login

routeros = login('admin', 'abc123abc', '192.168.88.1')

output = routeros('/system/identity/print')
# Extract the one identity string from the list of dictionaries
print(output[0]['name'])

 

Posted by Uli Köhler in MikroTik, Python

Netmiko MikroTik RouterOS SSH key login example

In our previous example Netmiko MikroTik RouterOS minimal example we showed how to login to a RouterOS device using netmikoand password-based login.

#!/usr/bin/env python3  
from netmiko import ConnectHandler
import os.path
mikrotik = {
    'device_type': 'mikrotik_routeros',
    'host':   '192.168.88.1',
    'username': 'admin',
    'key_file': os.path.expanduser("~/.ssh/id_mikrotik"),
}
with ConnectHandler(**mikrotik) as mikrotik_connection:
    print(mikrotik_connection.send_command(f'/system/identity/print', cmd_verify=False))

 

Example output:

name: MySwitch01

 

Posted by Uli Köhler in MikroTik, Networking, Python

Does MikroTik RouterOS support secp384r1 certificates

Yes, RouterOS 7.9+ supports certificates with secp384r1 keys.

RouterOS versions before 7.9 possibly also support secp384r1 certificates but I have no older RouterOS available for testing at the moment.

Posted by Uli Köhler in MikroTik, Security

NodeJS MikroTik PoE status query example

This example builds on our previous posts NodeJS Mikrotik API minimal example and MikroTik RouterOS: How to power-cycle PoE using the terminal.

The following code will print the PoE status on Port ether5 on the given MikroTik device using the MikroTik API.

import * as MikroNode from 'mikrotik' ;

const host = "192.168.88.1";
const username = "admin";
const password = "admin1234"; // Hope that's not your real password ;)

const connection = MikroNode.getConnection(host, username, password, {
    closeOnDone : true
});

connection.getConnectPromise().then(function(conn) {
    conn.getCommandPromise(['/interface/ethernet/poe/print', '?name=ether5']).then(values => {
        console.log(values);
    }, reason => {
        console.log('Error while running command: ' + JSON.stringify(reason));
    });
}).catch(reason =>  {
    console.log('Error while connecting: ' + JSON.stringify(reason));
});

Example output:

[
  {
    '.id': '*5',
    name: 'ether5',
    'poe-out': 'forced-on',
    'poe-priority': '10',
    'poe-lldp-enabled': 'false',
    'power-cycle-ping-enabled': 'false',
    'power-cycle-interval': 'none',
    '.about': 'poe-out status: power_reset'
  }
]

If the PoE is currently being power-cycled, this will print:

[
  {
    '.id': '*5',
    name: 'ether5',
    'poe-out': 'forced-on',
    'poe-priority': '10',
    'poe-lldp-enabled': 'false',
    'power-cycle-ping-enabled': 'false',
    'power-cycle-interval': 'none',
    '.about': 'poe-out status: power_reset'
  }
]

 

Posted by Uli Köhler in MikroTik, NodeJS, PoE

MikroTik RouterOS: How to power-cycle PoE using the terminal

/interface/ethernet/poe/power-cycle ether-MyAccessPoint duration=5

 

Posted by Uli Köhler in MikroTik

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}}

 

Posted by Uli Köhler in MikroTik, NodeJS

How to fix MikroTik “Couldn’t add new IPv6 Pool – prefix length cannot be smaller than prefix (6)”?

Problem:

You are trying to add a new IPv6 pool with settings such as

But when you click OK, you see an error message Couldn't add new IPv6 Pool - prefix length cannot be smaller than prefix (6)

Solution:

You need to add the prefix length – e.g. /64 to the Prefix field as well:

Now click OK or apply and the error will disappear.

Important note: You might want to use a different Prefix Length here (typically it is smaller than the e.g. /64 at the end of the Prefix field so multiple prefixes can be extracted from the given pool.

Posted by Uli Köhler in MikroTik

How to disable telnet on RouterOS or CHR (Cloud Hosted Router)

When you have a fresh install of RouterOS or CHR (MikroTik Cloud Hosted Router), telnet access is enabled by default. Since you typically want to access the router using SSH, WinBox or WebFig instead of telnet, you can – and should – disable it entirely.

In order disable telnet, login to your router using SSH or WinBox and run the following command:

/ip/service/disable telnet

 

Posted by Uli Köhler in MikroTik, Networking

How to enable NTP client on RouterOS or CHR (Cloud Hosted Router)

When you have a fresh install of RouterOS or CHR (MikroTik Cloud Hosted Router), the NTP client is not enabled by default.

In order to enable it, login to your router using SSH or WinBox and run the following command:

/system/ntp/client/ set enabled=yes servers=de.pool.ntp.org

Depending on your location, you might want to choose a suitable pool of NTP servers.

Posted by Uli Köhler in MikroTik, Networking

How to use Let’s Encrypt certificate for HTTPS API service on MikroTik RouterOS or CHR (Cloud Hosted Router)

Once you’ve setup a Let’s Encrypt certificate on your MikroTik RouterOS or CHR router, you can configure the API service to use it.

Login to your router using ssh, e.g. ssh [email protected].

Now copy-and-paste the following:

/ip/service set api-ssl certificate=[/certificate find where name~"^letsencrypt.*"]

This has been tested only in the circumstance that one letsencrypt certificate exists. I will update this post once I get around to testing it with multiple (renewed) certificates.

Posted by Uli Köhler in MikroTik, Networking

How to enable Let’s Encrypt & HTTPS on MikroTik CHR (Cloud hosted router)

Once you have installed your MikroTik CHR router on your server, you don’t want to access the webinterface using the unencrypted HTTP protocol.

Instead, follow these steps to enable HTTPS using Let’s Encrypt certificates which come built-in with recent RouterOS versions.

First, configure your DNS to point some domain name – e.g. chr.mydomain.com to your server’s IP address. TCP port 80 on the IP address the domain name points to must reach the CHR server.

Then, login to the CHR using ssh. This connection is encrypted. Run the following commands:

/certificate/enable-ssl-certificate dns-name=chr.mydomain.com

and

/ip/service/enable www-ssl

Example output:

[admin@MikroTik] > /certificate/enable-ssl-certificate dns-name=chr.mydomain.com
  progress: [success] ssl certificate updated

[admin@MikroTik] > /ip/service/enable www-ssl

After that (if the certificate could be generated successfully), your router will be reachable via https://chr.mydomain.com

Posted by Uli Köhler in MikroTik, Networking

How to disable all DHCP servers on MikroTik using SSH / CLI

The following command will disable (but not delete) all DHCP servers on MikroTik routers:

/ip/dhcp-server/disable [ find ]

 

Posted by Uli Köhler in MikroTik

How to remove ALL firewall rules on MikroTik Router

You can remove all static firewall rules on a MikroTik router using

/ip/firewall/filter/remove [ find where !dynamic ]

This will delete all the rules and there will be no way to recover them!

 

Posted by Uli Köhler in MikroTik, Networking

How to create directory on RouterOS using the terminal

As of RouterOS 7.6 there is no official command to create a directory on a RouterOS filesystem. However, there’s a trick involving a SMB share. By creating the SMB share, RouterOS will create the directory. After that, you can delete the SMB share.

The following script will create the backups directory:

/ip smb shares add name=deleteme directory=backups ; /ip smb shares remove [find name=deleteme]')
Posted by Uli Köhler in MikroTik, Networking

How to delete file(s) by regex filename on RouterOS

The following RouterOS command will delete all files starting with backup-:

/file/remove [/file find where name~"^backup-.*\$"]

 

Posted by Uli Köhler in MikroTik, Networking

How to delete file on RouterOS by filename using terminal or SSH (minimal example)

In order to delete a file named mybackup.backup on a RouterOS device using the terminal, use the following command:

/file/remove [find name="mybackup.backup"]

 

Posted by Uli Köhler in MikroTik, Networking

Netmiko MikroTik RouterOS minimal example

This example prints the identity (i.e. user-defined name) of the switch/router at IP address 10.0.0.1 with password abc123abc.

from netmiko import ConnectHandler
mikrotik = {
    'device_type': 'mikrotik_routeros',
    'host':   '10.0.0.1',
    'username': 'admin',
    'password': 'abc123abc'
}

mikrotik_connection = ConnectHandler(**mikrotik)
print(mikrotik_connection.send_command(f'/system/identity/print', cmd_verify=False))

Example output:

name: MySwitch01

 

Posted by Uli Köhler in MikroTik, Networking, Python

MikroTik User Manager (RADIUS): Add user with VLAN

The following RouterOS terminal command adds a User Manager user assigned to a VLAN with ID 998. This setup is compatible with Unifi access points.

/user-manager user add attributes=Tunnel-Type:13,Tunnel-Medium-Type:6,Tunnel-Private-Group-ID:998 name=myuser password=uNah2ieghi

Note that Tunnel-Type:13,Tunnel-Medium-Type:6 will always stay the same, they will tell RADIUS to assign a VLAN.

In WebFig, the same config looks like this:

In WinBox, these settings look like this:

Posted by Uli Köhler in MikroTik, Networking

MikroTik RouterOS Wake-on-LAN (magic packet) script example

On RouterOS, we can create a simple Wake-on-LAN script using a MAC address using

/tool/wol mac=DC:4A:3E:7A:87:12 interface=bridge

 

Posted by Uli Köhler in MikroTik, Networking

MikroTik scripting: simple foreach example

The following example uses MikroTik scripting to iterate over all ethernet interfaces and print the name of the interface:

foreach v in=[/interface/ethernet find] do={
    :put [/interface/ethernet get $v value-name=name]
}

Example output:

[admin@MySwitch] > foreach v in=[/interface/ethernet find] do={:put [/interface/ethernet get $v value-name=name]}
ether1
sfp-CoreSwitch-Uplink
sfp-sfpplus3
sfp-NAS
sfp-Virtualization
sfp-WAN
sfp-sfpplus4
sfp-sfpplus7
sfp-sfpplus8

 

Posted by Uli Köhler in MikroTik