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 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 <flags>
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[int(errorIndex) - 1][0] or "?",)
)
else:
for varBind in varBinds:
print(" = ".join([x.prettyPrint() for x in varBind]))
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
- Custom Device Labels in “The Dude” nms
- MikroTik Tutorial: How to recover RouterOS passwords from a backup file
- MikroTik: L2TP/IPsec VPN Firewall Rules
- MikroTik Router as a SCADA Serial Server
- MikroTik Config: cAP Lite Wifi Router w/L2TP VPN & Guest Wifi
2 Replies to “Reboot a MikroTik router with SNMP set (Python Script)”
Great! Perfect solution. Thank you.
Hello, i am leveraging your script to set some parameters for different modems. but i am rnninginto an error “TypeError: ‘ContextData’ object does not support indexing”
any thoughts? thank you in advance