· MikroTik Tutorial  · 2 min read

Reboot a MikroTik router with SNMP set (Python Script)

Here is a proof of concept python script I wrote to remotely reboot a MikroTik router using a SNMP set command. SNMP must be enabled on the router and a community string must be setup with write...

This post was originally published on jcutrer.com (WordPress) and has been migrated to the archive.

Here is a proof of concept python script I wrote to remotely reboot a MikroTik router using a SNMP set command. SNMP must be enabled on the router and a community string must be setup with write access for this script to work.

When executed with a valid community string the target router will immediately reboot. I understand this is somewhat novel but someone may find it useful.

The script has two python dependencies python-fire and pysnmp. Here are the commands to install these libraries.

pip install fire
pip install pysnmp

Command line arguments

C:\> python reboot_mikrotik.py --help

INFO: Showing help with the command 'reboot_mikrotik.py -- --help'.

NAME
    reboot_mikrotik.py - Reboot MikroTik router with SNMP

SYNOPSIS
    reboot_mikrotik.py HOST 

DESCRIPTION
    Reboot MikroTik router with SNMP

POSITIONAL ARGUMENTS
    HOST

FLAGS
    --community=COMMUNITY
    --port=PORT

NOTES
    You can also use flags syntax for POSITIONAL ARGUMENTS

Usage Example

C:\> python reboot_mikrotik.py 192.168.1.1 --community=my-write-string

reboot_mikrotik.py Source Code

import fire
from pysnmp.hlapi import *

def reboot(host, community="public", port=161):
    """Reboot MikroTik router with SNMP"""
    errorIndication, errorStatus, errorIndex, varBinds = next(
        setCmd(
            SnmpEngine(),
            CommunityData(community, mpModel=0),
            UdpTransportTarget((host, port)),
            ContextData(),
            ObjectType(ObjectIdentity("1.3.6.1.4.1.14988.1.1.7.1.0"), OctetString("1")),
        )
    )

    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print(
            "%s at %s"
            % (errorStatus.prettyPrint(), errorIndex and varBinds[0] or "?",)
        )
    else:
        for varBind in varBinds:
            print(" = ".join())

if __name__ == "__main__":

    fire.Fire(reboot)

The script is very short, sweet and to the point. It leverages the python-fire library from Google and pysnmp does the heavy lifting when it comes to SNMP.

I am also working on a similar script that first checks the router’s uptime and only reboots the device if it has been up for x number of days. Would this be useful to anybody? Let me know in the comments below.

More MikroTik Articles

More Python Articles

Comments are disabled (Giscus not yet configured).

Back to archive