Code Monkey home page Code Monkey logo

routeros_api's Introduction

RouterOS API

Python API for MikroTik RouterOS. Simple and easy to use.

WARNING for old users:

Project has changes it's structure and import signature.

Features:

  • Easy to use;
  • Standard RouterOS API syntax;
  • SSL;
  • Verbose.

Find this project on PyPI.org.

Installation

python -m pip install laiarturs-ros-api

Usage:

Default configuration:

Python code:

import ros_api

router = ros_api.Api('192.168.88.1')
r = router.talk('/system/identity/print')
print(r)

Output:

[{'name': 'MikroTik'}]

Username, password, port:

Python code:

import ros_api

router = ros_api.Api('10.21.0.100', user='Bob', password='St4ong0nE', port=15811)
r = router.talk('/ip/address/print')
print(r)

Output:

[{'.id': '*5', 'address': '10.21.0.100/24', 'network': '10.21.0.0','interface': 'ether1',
'actual-interface': 'ether1', 'invalid': 'false', 'dynamic': 'false', 'disabled': 'false'}]

SSL and verbose:

On RouterOS router create certificate and assign it to api-ssl service.

RouterOS:

/certificate
add name=ca-template common-name=myCa key-usage=key-cert-sign,crl-sign
add name=server-template common-name=server                           
sign ca-template ca-crl-host=10.21.0.100 name=myCa                         
sign server-template ca=myCa name=server

/ip service
set [find name=api-ssl] certificate=server

More info: MikroTik Wiki.

Python code:

import ros_api

router = ros_api.Api('10.21.0.100', user='SysAdmin', password='Meeseeks', verbose=True, use_ssl=True)
r = router.talk('/interface/wireless/enable\n=numbers=0')
print(r)

Output:

>>>  /login
>>>  =name=SysAdmin
>>>  =password=Meeseeks

<<<  !done

>>>  /interface/wireless/enable
>>>  =numbers=0

<<<  !done

[]

How it works:

Python3 module routeros_api.py contains class Api.

__init__()

By initialising this class it creates socket, connects and logs in. Api class __init__() arguments:

Argument Description
address str of IP address or host of RouterOS router on which it can be reached.
user str of username on router, default='admin'.
password str of password of user on router, default=''.
use_ssl bool whether to use SSL, default=False.
port int on which port to connect to router, default=8728, ssl default=8729.
verbose bool whether to print conversation with router, default=False.
context ssl instance for creating ssl connection, default is created, but it can be adjusted.
timeout float in seconds to set timeout on socket blocking operations, default=None.

Python code:

router = Api(address='192.168.10.1', user='Juri', password='L0vE$aun@', 
             use_ssl=True, port=8730, verbose=False, context=ctx, timeout=1)

talk()

To send commands to router use talk() method of Api class. talk() take one argument - message:

Argument Description
message str, tuple or list of strings or tuples. It is possible to send multiple commands bundled in a list.

Python code:

message = [('/system/note/set', '=note=Multi line\nnote for the Router!'), '/system/note/print']
r = router.talk(message)
print(r)

Output:

[[], [{'show-at-login': 'true', 'note': 'Multi line\nnote for the Router!'}]]

If property values you want to send to router contains spaces or linebreaks, sentence must be divided in words and then passed to talk() as tuple. Otherwise you can send sentences as strings and it will be divided in words where there is space or linebreak.

Method talk() returns list containing replies from router. In this case there are two replies, because message contained two sentences. Actions like set, add, enable etc. usually returns empty list, however, print, monitor and others returns list with dict inside containing reply from router.

Messages use RouterOS API syntax. More info: MikroTik Wiki.

routeros_api's People

Contributors

blackstrip avatar david-pili avatar kalvisan avatar laiarturs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

routeros_api's Issues

License

What are you're thoughts on changing to a more permissive license with this? Maybe MIT/BSD/Apache or at the very least LGPLv3 instead of GLPv3 to allow linking without inheriting GPL from the library.

I'm of the opinion that base libraries like this benefit from being under a more permissive license to encourage adoption in a broader range of projects.

If you're open to a change like this it'd be better to do it sooner rather then later, right now it's just you and I who need to consent to a license change.

no LoginError raising

Hi

There is no LoginError raising in login() method both on old (under 6.43) and new (above 6.43) RourerOS.

Reply is always this when password or username is nor correct:
[['!trap', '=message=invalid user name or password (6)'], ['!done']] at new RouterOS
and
[['!trap', '=message=cannot log in'], ['!done']] at old RouterOS

So there is no 'Error' str in reply

I've changed

  elif 'Error' in reply:
        # Else if there was some kind of error during login process
        self.log('Error in login process - {}'.format(reply))
        raise LoginError('Login ' + reply)

->

    elif len(reply[0]) == 2 and reply[0][0] == '!trap':
        # Else if there was some kind of error during login process
        self.log('Error in login process - {}'.format(reply))
        raise LoginError(f'Login {reply}')

and

       self.log('Logged in successfully!')
        return self.communicate(sentence)

->

        reply = self.communicate(sentence)
        if len(reply[0]) == 2 and reply[0][0] == '!trap':
            # Else if there was some kind of error during login process
            self.log('Error in login process - {}'.format(reply))
            raise LoginError(f'Login {reply}')
        else:
            self.log('Logged in successfully!')
            return self.communicate(sentence)

So it is working good now

error en el logueo mikrotik v7

hay problema para conectarse a la api sale este error.

PS E:\Documents\pyton project> & "C:/Users/Juan Francisco/AppData/Local/Programs/Python/Python310/python.exe" "e:/Documents/pyton project/api mikrotik/ejemplo.py"
Traceback (most recent call last):
File "e:\Documents\pyton project\api mikrotik\ejemplo.py", line 1, in
from routeros_api import Api
ImportError: cannot import name 'Api' from 'routeros_api' (C:\Users\Juan Francisco\AppData\Local\Programs\Python\Python310\lib\site-packages\routeros_api_init_.py)
PS E:\Documents\pyton project>

no se si yo estoy ejecutando mal el proyecto

Encoding problem

Thank you for your project. I am currently encountering an issue where I am getting a strange string after printing in Python.

How to decode it back?

ChineseName: 遂宁-家(核心)

ROS encoding: \CB\EC\C4\FE-\BC\D2(\BA\CB\D0\C4)

python print: \\xcb\\xec\\xc4\\xfe-\\xbc\\xd2(\\xba\\xcb\\xd0\\xc4)

Linux multi-line words get broken into multiple words

On Linux Multiline words get caught by reply = self.communicate(sentence.split())
sentence.split() catches the \n in the multiline word and sends each line as it's own word, it also splits on whitespaces. I've fixed this by changing it to reply = self.communicate(sentence.split('\r\n')) but I'm not too happy with this either as I suspect there would still be issues on windows. Are you open to splitting sentences into words with some other delimiter?

Also, thanks for the great work your API implementation is far far better than the default Mikrotik one :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.