pax_global_header00006660000000000000000000000064135606263100014514gustar00rootroot0000000000000052 comment=5fab07f90d781b6bc569690a71bca26f0cbbd988 librouteros-3.0.0/000077500000000000000000000000001356062631000140655ustar00rootroot00000000000000librouteros-3.0.0/.bumpversion.cfg000066400000000000000000000003141356062631000171730ustar00rootroot00000000000000[bumpversion] current_version = 3.0.0 commit = True tag = True tag_name = {new_version} message = Release {new_version} [bumpversion:file:setup.py] [bumpversion:file:CHANGELOG.rst] search = UNRELEASED librouteros-3.0.0/.github/000077500000000000000000000000001356062631000154255ustar00rootroot00000000000000librouteros-3.0.0/.github/FUNDING.yml000066400000000000000000000000201356062631000172320ustar00rootroot00000000000000patreon: luqasz librouteros-3.0.0/.gitignore000066400000000000000000000003521356062631000160550ustar00rootroot00000000000000#python compiled files *.py[cod] __pycache__ #virtual env .env #package related files / dirs *.deb dist build sdist MANIFEST .project *.egg-info #pytest cache .cache .pytest_cache # IDE stuff .idea .pydevproject .settings .vscode librouteros-3.0.0/.pylintrc000066400000000000000000000366471356062631000157520ustar00rootroot00000000000000[MASTER] # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. extension-pkg-whitelist= # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS # Add files or directories matching the regex patterns to the blacklist. The # regex matches against base names, not paths. ignore-patterns= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the # number of processors available to use. jobs=0 # Control the amount of potential inferred values when inferring a single # object. This can help the performance when dealing with large functions or # complex, nested conditions. limit-inference-results=100 # List of plugins (as comma separated values of python module names) to load, # usually to register additional checkers. load-plugins= # Pickle collected data for later comparisons. persistent=yes # Specify a configuration file. #rcfile= # When enabled, pylint would attempt to guess common misconfiguration and emit # user-friendly hints instead of false-positive error messages. suggestion-mode=yes # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. confidence= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once). You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use "--disable=all --enable=classes # --disable=W". disable=missing-module-docstring, missing-class-docstring, missing-function-docstring, unidiomatic-typecheck, logging-format-interpolation, # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). See also the "--disable" option for examples. enable=c-extension-no-member [REPORTS] # Python expression which should return a score less than or equal to 10. You # have access to the variables 'error', 'warning', 'refactor', and 'convention' # which contain the number of messages in each category, as well as 'statement' # which is the total number of statements analyzed. This score is used by the # global evaluation report (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details. #msg-template= # Set the output format. Available formats are text, parseable, colorized, json # and msvs (visual studio). You can also give a reporter class, e.g. # mypackage.mymodule.MyReporterClass. output-format=text # Tells whether to display a full report or only the messages. reports=no # Activate the evaluation score. score=yes [REFACTORING] # Maximum number of nested blocks for function / method body max-nested-blocks=5 # Complete name of functions that never returns. When checking for # inconsistent-return-statements if a never returning function is called then # it will be considered as an explicit return statement and no message will be # printed. never-returning-functions=sys.exit [LOGGING] # Format style used to check logging format string. `old` means using % # formatting, `new` is for `{}` formatting,and `fstr` is for f-strings. logging-format-style=old # Logging modules to check that the string format arguments are in logging # function parameter format. logging-modules=logging [SPELLING] # Limits count of emitted suggestions for spelling mistakes. max-spelling-suggestions=4 # Spelling dictionary name. Available dictionaries: none. To make it work, # install the python-enchant package. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains the private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to the private dictionary (see the # --spelling-private-dict-file option) instead of raising a message. spelling-store-unknown-words=no [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME, XXX, TODO [TYPECHECK] # List of decorators that produce context managers, such as # contextlib.contextmanager. Add to this list to register other decorators that # produce valid context managers. contextmanager-decorators=contextlib.contextmanager # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E1101 when accessed. Python regular # expressions are accepted. generated-members= # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # Tells whether to warn about missing members when the owner of the attribute # is inferred to be None. ignore-none=yes # This flag controls whether pylint should warn about no-member and similar # checks whenever an opaque object is returned when inferring. The inference # can return multiple potential results while evaluating a Python object, but # some branches might not be evaluated, which results in partial inference. In # that case, it might be useful to still emit no-member and other checks for # the rest of the inferred objects. ignore-on-opaque-inference=yes # List of class names for which member attributes should not be checked (useful # for classes with dynamically set attributes). This supports the use of # qualified names. ignored-classes=optparse.Values,thread._local,_thread._local # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis). It # supports qualified module names, as well as Unix pattern matching. ignored-modules= # Show a hint with possible names when a member name was not found. The aspect # of finding the hint is based on edit distance. missing-member-hint=yes # The minimum edit distance a name should have in order to be considered a # similar match for a missing member name. missing-member-hint-distance=1 # The total number of similar names that should be taken in consideration when # showing a hint for a missing member. missing-member-max-choices=1 # List of decorators that change the signature of a decorated function. signature-mutators= [VARIABLES] # List of additional names supposed to be defined in builtins. Remember that # you should avoid defining new builtins when possible. additional-builtins= # Tells whether unused global variables should be treated as a violation. allow-global-unused-variables=yes # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_, _cb # A regular expression matching the name of dummy variables (i.e. expected to # not be used). dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ # Argument names that match this expression will be ignored. Default to name # with leading underscore. ignored-argument-names=_.*|^ignored_|^unused_ # Tells whether we should check for unused import in __init__ files. init-import=no # List of qualified module names which can have objects that can redefine # builtins. redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io [FORMAT] # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format= # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Maximum number of characters on a single line. max-line-length=100 # Maximum number of lines in a module. max-module-lines=1000 # List of optional constructs for which whitespace checking is disabled. `dict- # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. # `trailing-comma` allows a space between comma and closing bracket: (a, ). # `empty-line` allows space-only lines. no-space-check=trailing-comma # Allow the body of a class to be on the same line as the declaration if body # contains single statement. single-line-class-stmt=no # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no [SIMILARITIES] # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no # Minimum lines number of a similarity. min-similarity-lines=4 [BASIC] # Naming style matching correct argument names. argument-naming-style=snake_case # Regular expression matching correct argument names. Overrides argument- # naming-style. #argument-rgx= # Naming style matching correct attribute names. attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. #attr-rgx= # Bad variable names which should always be refused, separated by a comma. bad-names=foo, bar, baz, toto, tutu, tata # Naming style matching correct class attribute names. class-attribute-naming-style=snake_case # Regular expression matching correct class attribute names. Overrides class- # attribute-naming-style. #class-attribute-rgx= # Naming style matching correct class names. class-naming-style=PascalCase # Regular expression matching correct class names. Overrides class-naming- # style. #class-rgx= # Naming style matching correct constant names. const-naming-style=UPPER_CASE # Regular expression matching correct constant names. Overrides const-naming- # style. #const-rgx= # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 # Naming style matching correct function names. function-naming-style=snake_case # Regular expression matching correct function names. Overrides function- # naming-style. #function-rgx= # Good variable names which should always be accepted, separated by a comma. good-names= # Include a hint for the correct naming format with invalid-name. include-naming-hint=no # Naming style matching correct inline iteration names. inlinevar-naming-style=any # Regular expression matching correct inline iteration names. Overrides # inlinevar-naming-style. #inlinevar-rgx= # Naming style matching correct method names. method-naming-style=camelCase # Regular expression matching correct method names. Overrides method-naming- # style. #method-rgx= # Naming style matching correct module names. module-naming-style=snake_case # Regular expression matching correct module names. Overrides module-naming- # style. #module-rgx= # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=^_ # List of decorators that produce properties, such as abc.abstractproperty. Add # to this list to register other decorators that produce valid properties. # These decorators are taken in consideration only for invalid-name. property-classes=abc.abstractproperty # Naming style matching correct variable names. variable-naming-style=snake_case # Regular expression matching correct variable names. Overrides variable- # naming-style. #variable-rgx= [STRING] # This flag controls whether the implicit-str-concat-in-sequence should # generate a warning on implicit string concatenation in sequences defined over # several lines. check-str-concat-over-line-jumps=no [IMPORTS] # List of modules that can be imported at any level, not just the top level # one. allow-any-import-level= # Allow wildcard imports from modules that define __all__. allow-wildcard-with-all=no # Analyse import fallback blocks. This can be used to support both Python 2 and # 3 compatible code, which means that the block might have code that exists # only in one or another interpreter, leading to false positives when analysed. analyse-fallback-blocks=no # Deprecated modules which should not be used, separated by a comma. deprecated-modules=optparse,tkinter.tix # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled). ext-import-graph= # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled). import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled). int-import-graph= # Force import order to recognize a module as part of the standard # compatibility libraries. known-standard-library= # Force import order to recognize a module as part of a third party library. known-third-party=enchant # Couples of modules and preferred modules, separated by a comma. preferred-modules= [CLASSES] # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__, __new__, setUp, __post_init__ # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict, _fields, _replace, _source, _make # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=cls [DESIGN] # Maximum number of arguments for function / method. max-args=5 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Maximum number of boolean expressions in an if statement (see R0916). max-bool-expr=5 # Maximum number of branch for function / method body. max-branches=12 # Maximum number of locals for function / method body. max-locals=15 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of public methods for a class (see R0904). max-public-methods=20 # Maximum number of return / yield for function / method body. max-returns=6 # Maximum number of statements in function / method body. max-statements=50 # Minimum number of public methods for a class (see R0903). min-public-methods=2 [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "BaseException, Exception". overgeneral-exceptions=BaseException, Exception librouteros-3.0.0/.travis.yml000066400000000000000000000013341356062631000161770ustar00rootroot00000000000000notifications: email: on_success: change on_failure: change dist: bionic sudo: false language: python cache: pip python: - 3.6 - 3.7 addons: apt: packages: - qemu-system-i386 - qemu-utils install: - pip install -U -r requirements.tests.txt - pip install -e . script: - pylint librouteros - yapf -dr librouteros - yapf -dr tests - wget --quiet netng.pl/routeros_test_images/routeros_6.33.3.qcow2 -O images/routeros_6.33.3.qcow2 - wget --quiet netng.pl/routeros_test_images/routeros_6.44.5.qcow2 -O images/routeros_6.44.5.qcow2 - pytest tests/unit - pytest -n auto tests/integration deploy: provider: pypi user: lkostka password: $PYPI_PASS on: tags: true python: 3.8 librouteros-3.0.0/CHANGELOG.rst000066400000000000000000000025661356062631000161170ustar00rootroot000000000000003.0.0 ---------- - Introduce query support. - Path object for easy query and common operations. - yield each item instead of returning tuple of items. Greatly reduces memory usage. - Drop pre python 3.6 support. - Replace pylava with pylint. - Add yapf formatter. - Replace py.path with builtin pathlib. - connect() accepts only one login_method parameter. - Drop socker exceptions wrapping. - Remove ConnectionError exception. - Renamed LibError to LibRouterosError. - Changed exceptions inheritance. - Removed joinPath() 2.4.0 ---------- - Add query support. #11 2.3.1 ---------- - Fix raising TrapError when failed to login. #63 2.3.0 ---------- - Add rawCmd() method for passing custom queries. 2.2.0 ---------- - Excplicit login_method parameter for login using new or old auth method. 2.1.1 ---------- - Fix testing with pip >= 18.x 2.1.0 ---------- - Support new auth method introduced in 6.43 2.0.0 ------ - Drop support for python 3.2, 3.3 - Added ssl / apis support 1.0.5 ------ - Fix loop in SocketTransport.read() (pull request #23) 1.0.4 ------ - Fix multiple byte word encoding during reading (issue #12) 1.0.3 ------ - Provide option to use user defined encoding 1.0.2 ------ - Fix E722 do not use bare except [pep8] - Test with python 3.6 - Integration tests with qemu emulated RouterOs image - Pin setuptools to higher version 1.0.1 ------ - First release librouteros-3.0.0/LICENSE000066400000000000000000000432541356062631000151020ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. librouteros-3.0.0/README.rst000066400000000000000000000001601356062631000155510ustar00rootroot00000000000000Documentation ============= Documentation resides over at `readthedocs `_ librouteros-3.0.0/apicli.py000077500000000000000000000036771356062631000157200ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """Command line interface for debugging purpouses.""" import logging import getpass from argparse import ArgumentParser from sys import stdout, stdin from select import select from os import linesep from librouteros import connect, ConnectionError, TrapError, FatalError argParser = ArgumentParser(description='mikrotik api cli interface') argParser.add_argument( 'host', type=str, help="host to with to connect. may be fqdn, ipv4 or ipv6 address") argParser.add_argument('-u', '--user', type=str, required=True, help="username") argParser.add_argument( '-p', '--port', type=int, default=8728, help="port to connect to (default 8728)") args = argParser.parse_args() mainlog = logging.getLogger('librouteros') console = logging.StreamHandler(stdout) mainlog.setLevel(logging.DEBUG) formatter = logging.Formatter(fmt='%(message)s') console.setFormatter(formatter) mainlog.addHandler(console) def selectloop(api): snt = [] while True: proto = api.protocol sk = proto.transport.sock rlist, wlist, errlist = select([sk, stdin], [], [], None) if sk in rlist: proto.readSentence() if stdin in rlist: line = stdin.readline() line = line.split(linesep) line = line[0] if line: snt.append(line) elif not line and snt: proto.writeSentence(snt[0], *snt[1:]) snt = [] def main(): pw = getpass.getpass() try: api = connect(args.host, args.user, pw, logger=mainlog) except (TrapError, ConnectionError) as err: exit(err) except KeyboardInterrupt: pass else: try: selectloop(api) except KeyboardInterrupt: pass except (ConnectionError, FatalError) as e: print(e) finally: api.close() if __name__ == '__main__': main() librouteros-3.0.0/docs/000077500000000000000000000000001356062631000150155ustar00rootroot00000000000000librouteros-3.0.0/docs/.gitignore000066400000000000000000000000071356062631000170020ustar00rootroot00000000000000_build librouteros-3.0.0/docs/Makefile000066400000000000000000000127201356062631000164570ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/librouteros.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/librouteros.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/librouteros" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/librouteros" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." librouteros-3.0.0/docs/api_analysis.rst000066400000000000000000000133671356062631000202350ustar00rootroot00000000000000Api analysis ============ This document aims to cover in depth analysis of routeros API. Lines that begin with ``--->`` represent data received from a device. Linet that start with ``<---`` represent data send to a device. End of sentence is marked with ``EOS``. Succesfull login (pre 6.43) --------------------------- .. code-block:: none <--- /login <--- EOS ---> !done ---> =ret=xxxxxxxxxxxxxxxxxxxxx ---> EOS <--- /login <--- =name=admin <--- =response=xxxxxxxxxxxxxxx <--- EOS ---> !done ---> EOS Succesfull login (post 6.42) ---------------------------- .. code-block:: none <--- /login <--- =name=admin <--- =password=xxxxxxxxxxxxxxx <--- EOS ---> !done ---> EOS Failed login attempt (pre 6.43) ------------------------------- .. code-block:: none <--- /login <--- EOS ---> !done ---> =ret=xxxxxxxxxxxxxxxxxxxxx ---> EOS <--- /login <--- =name=admin <--- =response=xxxxxxxxxxxxxxxxxxxxx <--- EOS ---> !trap ---> =message=cannot log in ---> EOS ---> !done ---> EOS Logging off ----------- .. code-block:: none <--- /quit <--- EOS ---> !fatal ---> session terminated on request ---> EOS Multiple empty responses ------------------------ .. code-block:: none <--- /ip/service/print <--- =.proplist=comment <--- EOS ---> !re ---> EOS ---> !re ---> EOS ---> !re ---> EOS ---> !re ---> EOS ---> !re ---> EOS ---> !re ---> EOS ---> !re ---> EOS ---> !done ---> EOS Adding element -------------- .. code-block:: none <--- /ip/address/add <--- =address=192.168.1.1/24 <--- =interface=ether1 <--- EOS ---> !done ---> =ret=*3 ---> EOS Canceling ``listen`` -------------------- Command returns ``!trap`` which is not actually any error at all: .. code-block:: none <--- '/ip/address/listen' <--- '.tag=10' <--- EOS ---> '!re' ---> '.tag=10' ---> '=.id=*A' ---> '=address=1.1.1.1/32' ---> '=network=1.1.1.1' ---> '=interface=br-lan' ---> '=actual-interface=br-lan' ---> '=invalid=false' ---> '=dynamic=false' ---> '=disabled=false' ---> EOS ---> '!re' ---> '.tag=10' ---> '=.id=*A' ---> '=.dead=true' ---> EOS <--- '/cancel' <--- '=tag=10' <--- '.tag=20' <--- EOS ---> '!trap' ---> '.tag=10' ---> '=category=2' ---> '=message=interrupted' ---> EOS ---> '!done' ---> '.tag=20' ---> EOS ---> '!done' ---> '.tag=10' ---> EOS Fetching from url ----------------- .. code-block:: none <--- '/tool/fetch' <--- '=url=http://ping.online.net/10Mo.dat' <--- '.tag=1' <--- EOS ---> '!re' ---> '.tag=1' ---> '=status=connecting' ---> '=.section=0' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=731' ---> '=total=9765' ---> '=duration=1s' ---> '=.section=1' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=1579' ---> '=total=9765' ---> '=duration=2s' ---> '=.section=2' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=2427' ---> '=total=9765' ---> '=duration=3s' ---> '=.section=3' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=3275' ---> '=total=9765' ---> '=duration=4s' ---> '=.section=4' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=4139' ---> '=total=9765' ---> '=duration=5s' ---> '=.section=5' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=4987' ---> '=total=9765' ---> '=duration=6s' ---> '=.section=6' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=5839' ---> '=total=9765' ---> '=duration=7s' ---> '=.section=7' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=6687' ---> '=total=9765' ---> '=duration=8s' ---> '=.section=8' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=7551' ---> '=total=9765' ---> '=duration=9s' ---> '=.section=9' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=8415' ---> '=total=9765' ---> '=duration=10s' ---> '=.section=10' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=9279' ---> '=total=9765' ---> '=duration=12s' ---> '=.section=11' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=finished' ---> '=downloaded=9765' ---> '=total=9765' ---> '=duration=13s' ---> '=.section=12' ---> EOS ---> '!done' ---> '.tag=1' ---> EOS Canceling fetch --------------- .. code-block:: none <--- '/tool/fetch' <--- '=url=http://ping.online.net/10Mo.dat' <--- '.tag=1' <--- EOS ---> '!re' ---> '.tag=1' ---> '=status=connecting' ---> '=.section=0' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=18' ---> '=total=9765' ---> '=duration=0s' ---> '=.section=1' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=853' ---> '=total=9765' ---> '=duration=1s' ---> '=.section=2' ---> EOS <--- '/cancel' <--- '=tag=1' <--- EOS ---> '!trap' ---> '.tag=1' ---> '=category=2' ---> '=message=interrupted' ---> EOS ---> '!done' ---> EOS ---> '!done' ---> '.tag=1' ---> EOS librouteros-3.0.0/docs/conf.py000066400000000000000000000037361356062631000163250ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = '1.5' # Add any Sphinx extension module names here, as strings. # They can be extensions coming with Sphinx (named 'sphinx.ext.*') # or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = 'librouteros' copyright = u'Łukasz Kostka' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. language = 'en' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # The theme to use for HTML and HTML Help pages. html_theme = 'alabaster' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If true, links to the reST sources are added to the pages. html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. html_show_copyright = True # Output file base name for HTML help builder. htmlhelp_basename = 'librouteros' librouteros-3.0.0/docs/connect.rst000066400000000000000000000030151356062631000171770ustar00rootroot00000000000000Connect ======= Unencrypted ----------- .. code-block:: python from librouteros import connect api = connect( username='admin', password='abc', host='some.address.com', ) Encrypted --------- Before connecting, ``api-ssl`` service on routeros must be enabled. For more information on how to generate certificates see `MikroTik wiki `_. After that, create your default `SSLContext `_ and fine tune for your needs. Code below allows connecting to API without ceritficate. .. code-block:: python import ssl from librouteros import connect ctx = ssl.create_default_context() ctx.check_hostname = False ctx.set_ciphers('ADH:@SECLEVEL=0') api = connect( username='admin', password='abc', host='some.address.com', ssl_wrapper=ctx.wrap_socket, port=8729 ) Auth methods ------------ Starting from routeros ``6.43``, token auth method was replaced by plain text. By default library will use plain text method. You can force library to use token method: .. code-block:: python from librouteros.login import plain, token # for post 6.42 (plain text password) method = plain # for pre 6.43 (with token) method = token api = connect(username='admin', password='abc', host='some.address.com', login_method=method) .. note:: Library will not try different methods untill it will log in. librouteros-3.0.0/docs/contributing.rst000066400000000000000000000002751356062631000202620ustar00rootroot00000000000000Contributing ============ To submit a feature requests or a bug report, please use issues from within github. If you would like to submit a patch please contact author or use pull request. librouteros-3.0.0/docs/index.rst000066400000000000000000000021601356062631000166550ustar00rootroot00000000000000Librouteros - Routeros api implementation ========================================= .. image:: https://travis-ci.org/luqasz/librouteros.svg?branch=master :target: https://travis-ci.org/luqasz/librouteros :alt: Tests .. image:: https://img.shields.io/pypi/v/librouteros.svg :target: https://pypi.python.org/pypi/librouteros/ :alt: Latest PyPI version .. image:: https://img.shields.io/pypi/pyversions/librouteros.svg :target: https://pypi.python.org/pypi/librouteros/ :alt: Supported Python Versions .. image:: https://img.shields.io/pypi/l/librouteros.svg :target: https://pypi.python.org/pypi/librouteros/ :alt: License .. image:: https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg :target: https://saythanks.io/to/luqasz :alt: Say Thanks About _____ Python implementation of `routeros api `_. This library uses `semantic versioning `_. On major version things may break, so pin version in dependencies. .. toctree:: :maxdepth: 2 introduction connect path query api_analysis license contributing librouteros-3.0.0/docs/introduction.rst000066400000000000000000000007251356062631000202740ustar00rootroot00000000000000Introduction ============ Features -------- * Python type casting * Key and values stored in dictionary * Source address, port specification * TLS/SSL socket encryption * Logging support Limitations ----------- * No support for sentence tagging. * No asynchronous support for reading/writing Requirements ------------ * Python 3, with sufficiently recent versions of `pip` and `setuptools` * Mock (for runing unit tests). * `qemu` for running integration tests. librouteros-3.0.0/docs/license.rst000066400000000000000000000000671356062631000171740ustar00rootroot00000000000000License ------- .. include:: ../LICENSE :literal: librouteros-3.0.0/docs/path.rst000066400000000000000000000030241356062631000165020ustar00rootroot00000000000000Path object =========== ``Path`` object represents absolute command path within routeros. e.g. ``/ip/address``. You can traverse down in tree with ``join()`` method. Works same as python `join() `_. .. code-block:: python # First create desired path. interfaces = api.path('interface') # Traverse down into /interfaces/ethernet ethernet = interfaces.join('ethernet') # path() and join() accepts multiple arguments ips = api.path('ip', 'address') Get all ------- .. code-block:: python # Path objects are iterable tuple(interfaces) # This also will work, as well as anything else you can do with iterables for item in interfaces: print(item) Add --- .. code-block:: python # Will return newly created .id path.add(interface='ether1', address='172.31.31.1/24') Remove ------ .. code-block:: python # Pass each .id as an argument. path.remove('*1', '*2') .. note:: ``.id`` change on reboot. Always read them first. Update ------ .. code-block:: python params = {'disabled': True, '.id' :'*7'} path.update(**params) .. note:: ``.id`` change on reboot. Always read them first. Arbitrary command ----------------- For all other commands, call ``Path`` object directly. As a first argument, pass command that you wish to run without absolute path. .. code-block:: python script = api.path('system', 'script') # Will run /system/script/run with desired .id script('run', **{'.id': '*1'}) librouteros-3.0.0/docs/query.rst000066400000000000000000000026111356062631000167140ustar00rootroot00000000000000Query ===== Basic usage ----------- Get only ``name`` and ``disabled`` keys from all interfaces. .. code-block:: python from librouteros.query import Key # Each key must be created first in order to reference it later. name = Key('name') disabled = Key('disabled') for row in api.path('/interface').select(name, disabled): print(row) Advanced Usage -------------- Adding ``where()``, allows to fine tune serch criteria. Syntax is very simmilar to a SQL query. .. code-block:: python name = Key('name') disabled = Key('disabled') for row in api.path('/interface').select(name, disabled).where( disabled == False, Or( name == 'ether2', name == 'wlan-lan', ), ): Above code demonstrates how to select ``name``, ``disabled`` fields where each interface is disabled and ``name`` is equal to one of ``ether2``, ``wlan-lan``. If you do not specify any logical operation within `where()`, them it defaults to `And()`. Usable operators ---------------- ======== ========= operator example ======== ========= ``==`` ``name == 'ether2'`` ``!=`` ``name != 'ether2'`` ``>`` ``mtu > 1500`` ``<`` ``mtu < 1400`` ======== ========= Logical operators ----------------- ``And``, ``Or``. Ecah operator takes at least two expressions and performs a logical operation translating it to API query equivalents. librouteros-3.0.0/images/000077500000000000000000000000001356062631000153325ustar00rootroot00000000000000librouteros-3.0.0/images/.gitignore000066400000000000000000000000101356062631000173110ustar00rootroot00000000000000*.qcow2 librouteros-3.0.0/images/README.md000066400000000000000000000006001356062631000166050ustar00rootroot00000000000000# How to create qcow2 images. `VERSION` is exact routeros version number. ### Create disk image. ``` qemu-img create -f qcow2 routeros_VERSION.qcow2 64m ``` ### Install routeros. ``` qemu-system-x86_64 \ -m 64 \ -hda routeros_VERSION.qcow2 \ -net nic,model=virtio \ -cdrom ISO_FILE.iso \ ``` * Install every package except `kvm` * Add `dhcp-client` on `ether1` librouteros-3.0.0/librouteros/000077500000000000000000000000001356062631000164365ustar00rootroot00000000000000librouteros-3.0.0/librouteros/__init__.py000066400000000000000000000035311356062631000205510ustar00rootroot00000000000000# -*- coding: UTF-8 -*- from socket import create_connection from collections import ChainMap from librouteros.exceptions import ( ConnectionClosed, FatalError, ) from librouteros.connections import SocketTransport from librouteros.protocol import ApiProtocol from librouteros.login import ( plain, token, ) from librouteros.api import Api DEFAULTS = { 'timeout': 10, 'port': 8728, 'saddr': '', 'subclass': Api, 'encoding': 'ASCII', 'ssl_wrapper': lambda sock: sock, 'login_method': plain, } def connect(host, username, password, **kwargs): """ Connect and login to routeros device. Upon success return a Api class. :param host: Hostname to connecto to. May be ipv4,ipv6,FQDN. :param username: Username to login with. :param password: Password to login with. Only ASCII characters allowed. :param timeout: Socket timeout. Defaults to 10. :param port: Destination port to be used. Defaults to 8728. :param saddr: Source address to bind to. :param subclass: Subclass of Api class. Defaults to Api class from library. :param ssl_wrapper: Callable (e.g. ssl.SSLContext instance) to wrap socket with. :param login_method: Callable with login method. """ arguments = ChainMap(kwargs, DEFAULTS) transport = create_transport(host, **arguments) protocol = ApiProtocol(transport=transport, encoding=arguments['encoding']) api = arguments['subclass'](protocol=protocol) try: arguments['login_method'](api=api, username=username, password=password) return api except (ConnectionClosed, FatalError): transport.close() raise def create_transport(host, **kwargs): sock = create_connection((host, kwargs['port']), kwargs['timeout'], (kwargs['saddr'], 0)) sock = kwargs['ssl_wrapper'](sock) return SocketTransport(sock=sock) librouteros-3.0.0/librouteros/api.py000066400000000000000000000067041356062631000175700ustar00rootroot00000000000000# -*- coding: UTF-8 -*- from posixpath import join as pjoin from librouteros.exceptions import TrapError, MultiTrapError from librouteros.protocol import ( compose_word, parse_word, ) from librouteros.query import Query class Api: def __init__(self, protocol): self.protocol = protocol def __call__(self, cmd, **kwargs): """ Call Api with given command. Yield each row. :param cmd: Command word. eg. /ip/address/print :param kwargs: Dictionary with optional arguments. """ words = (compose_word(key, value) for key, value in kwargs.items()) self.protocol.writeSentence(cmd, *words) yield from self.readResponse() def rawCmd(self, cmd, *words): """ Call Api with given command and raw words. End user is responsible to properly format each api word argument. :param cmd: Command word. eg. /ip/address/print :param args: Iterable with optional plain api arguments. """ self.protocol.writeSentence(cmd, *words) yield from self.readResponse() def readSentence(self): """ Read one sentence and parse words. :returns: Reply word, dict with attribute words. """ reply_word, words = self.protocol.readSentence() words = dict(parse_word(word) for word in words) return reply_word, words def readResponse(self): """ Yield each sentence untill !done is received. :throws TrapError: If one !trap is received. :throws MultiTrapError: If > 1 !trap is received. """ traps = [] reply_word = None while reply_word != '!done': reply_word, words = self.readSentence() if reply_word == '!trap': traps.append(TrapError(**words)) elif reply_word in ('!re', '!done') and words: yield words if len(traps) > 1: raise MultiTrapError(*traps) if len(traps) == 1: raise traps[0] def close(self): self.protocol.close() def path(self, *path): return Path( path='', api=self, ).join(*path) class Path: """Represents absolute command path.""" def __init__(self, path, api): self.path = path self.api = api def select(self, key, *other): keys = (key, ) + other return Query(path=self, keys=keys, api=self.api) def __str__(self): return self.path def __repr__(self): return "<{module}.{cls} {path!r}>".format( module=self.__class__.__module__, cls=self.__class__.__name__, path=self.path, ) def __iter__(self): yield from self('print') def __call__(self, cmd, **kwargs): yield from self.api( self.join(cmd).path, **kwargs, ) def join(self, *path): """Join current path with one or more path strings.""" return Path( api=self.api, path=pjoin('/', self.path, *path).rstrip('/'), ) def remove(self, *ids): ids = ','.join(ids) tuple(self( 'remove', **{'.id': ids}, )) def add(self, **kwargs): ret = self( 'add', **kwargs, ) return tuple(ret)[0]['ret'] def update(self, **kwargs): tuple(self( 'set', **kwargs, )) librouteros-3.0.0/librouteros/connections.py000066400000000000000000000015041356062631000213320ustar00rootroot00000000000000# -*- coding: UTF-8 -*- from librouteros.exceptions import ConnectionClosed class SocketTransport: def __init__(self, sock): self.sock = sock def write(self, data): """ Write given bytes to socket. Loop as long as every byte in string is written unless exception is raised. """ self.sock.sendall(data) def read(self, length): """ Read as many bytes from socket as specified in length. Loop as long as every byte is read unless exception is raised. """ data = bytearray() while len(data) != length: data += self.sock.recv((length - len(data))) if not data: raise ConnectionClosed('Connection unexpectedly closed.') return data def close(self): self.sock.close() librouteros-3.0.0/librouteros/exceptions.py000066400000000000000000000023241356062631000211720ustar00rootroot00000000000000# -*- coding: UTF-8 -*- class LibRouterosError(Exception): """Base exception for all other.""" class ConnectionClosed(LibRouterosError): """Raised when connection have been closed.""" class ProtocolError(LibRouterosError): """Raised when e.g. encoding/decoding fails.""" class FatalError(ProtocolError): """Exception raised when !fatal is received.""" class TrapError(ProtocolError): """ Exception raised when !trap is received. :param int category: Optional integer representing category. :param str message: Error message. """ def __init__(self, message, category=None): self.category = category self.message = message super().__init__() def __str__(self): return str(self.message.replace('\r\n', ',')) def __repr__(self): return '{}({!r})'.format(self.__class__.__name__, str(self)) class MultiTrapError(ProtocolError): """ Exception raised when multiple !trap words have been received in one response. :param traps: TrapError instances. """ def __init__(self, *traps): self.traps = traps super().__init__() def __str__(self): return ', '.join(str(trap) for trap in self.traps) librouteros-3.0.0/librouteros/login.py000066400000000000000000000015531356062631000201240ustar00rootroot00000000000000from binascii import unhexlify, hexlify from hashlib import md5 def encode_password(token, password): #pylint: disable=redefined-outer-name token = token.encode('ascii', 'strict') token = unhexlify(token) password = password.encode('ascii', 'strict') hasher = md5() hasher.update(b'\x00' + password + token) password = hexlify(hasher.digest()) return '00' + password.decode('ascii', 'strict') def token(api, username, password): """Login using pre routeros 6.43 authorization method.""" sentence = api('/login') tok = tuple(sentence)[0]['ret'] encoded = encode_password(tok, password) tuple(api('/login', **{'name': username, 'response': encoded})) def plain(api, username, password): """Login using post routeros 6.43 authorization method.""" tuple(api('/login', **{'name': username, 'password': password})) librouteros-3.0.0/librouteros/protocol.py000066400000000000000000000127331356062631000206570ustar00rootroot00000000000000# -*- coding: UTF-8 -*- from struct import pack, unpack from logging import getLogger, NullHandler from librouteros.exceptions import ( ProtocolError, FatalError, ) LOGGER = getLogger('librouteros') LOGGER.addHandler(NullHandler()) def parse_word(word): """ Split given attribute word to key, value pair. Values are casted to python equivalents. :param word: API word. :returns: Key, value pair. """ mapping = {'yes': True, 'true': True, 'no': False, 'false': False} _, key, value = word.split('=', 2) try: value = int(value) except ValueError: value = mapping.get(value, value) return (key, value) def cast_to_api(value): """Cast python equivalent to API.""" mapping = {True: 'yes', False: 'no'} # this is necesary because 1 == True, 0 == False if type(value) == int: value = str(value) else: value = mapping.get(value, str(value)) return value def compose_word(key, value): """ Create a attribute word from key, value pair. Values are casted to api equivalents. """ return '={}={}'.format(key, cast_to_api(value)) class Encoder: def encodeSentence(self, *words): """ Encode given sentence in API format. :param words: Words to endoce. :returns: Encoded sentence. """ encoded = map(self.encodeWord, words) encoded = b''.join(encoded) # append EOS (end of sentence) byte encoded += b'\x00' return encoded def encodeWord(self, word): """ Encode word in API format. :param word: Word to encode. :returns: Encoded word. """ #pylint: disable=no-member encoded_word = word.encode(encoding=self.encoding, errors='strict') return Encoder.encodeLength(len(word)) + encoded_word @staticmethod def encodeLength(length): """ Encode given length in mikrotik format. :param length: Integer < 268435456. :returns: Encoded length. """ if length < 128: ored_length = length offset = -1 elif length < 16384: ored_length = length | 0x8000 offset = -2 elif length < 2097152: ored_length = length | 0xC00000 offset = -3 elif length < 268435456: ored_length = length | 0xE0000000 offset = -4 else: raise ProtocolError('Unable to encode length of {}'.format(length)) return pack('!I', ored_length)[offset:] class Decoder: @staticmethod def determineLength(length): """ Given first read byte, determine how many more bytes needs to be known in order to get fully encoded length. :param length: First read byte. :return: How many bytes to read. """ integer = ord(length) #pylint: disable=no-else-return if integer < 128: return 0 elif integer < 192: return 1 elif integer < 224: return 2 elif integer < 240: return 3 raise ProtocolError('Unknown controll byte {}'.format(length)) @staticmethod def decodeLength(length): """ Decode length based on given bytes. :param length: Bytes string to decode. :return: Decoded length. """ bytes_length = len(length) if bytes_length < 2: offset = b'\x00\x00\x00' xor = 0 elif bytes_length < 3: offset = b'\x00\x00' xor = 0x8000 elif bytes_length < 4: offset = b'\x00' xor = 0xC00000 elif bytes_length < 5: offset = b'' xor = 0xE0000000 else: raise ProtocolError('Unable to decode length of {}'.format(length)) decoded = unpack('!I', (offset + length))[0] decoded ^= xor return decoded class ApiProtocol(Encoder, Decoder): def __init__(self, transport, encoding): self.transport = transport self.encoding = encoding @staticmethod def log(direction_string, *sentence): for word in sentence: LOGGER.debug('{0} {1!r}'.format(direction_string, word)) LOGGER.debug('{0} EOS'.format(direction_string)) def writeSentence(self, cmd, *words): """ Write encoded sentence. :param cmd: Command word. :param words: Aditional words. """ encoded = self.encodeSentence(cmd, *words) self.log('<---', cmd, *words) self.transport.write(encoded) def readSentence(self): """ Read every word untill empty word (NULL byte) is received. :return: Reply word, tuple with read words. """ sentence = tuple(word for word in iter(self.readWord, '')) self.log('--->', *sentence) reply_word, words = sentence[0], sentence[1:] if reply_word == '!fatal': self.transport.close() raise FatalError(words[0]) return reply_word, words def readWord(self): byte = self.transport.read(1) # Early return check for null byte if byte == b'\x00': return '' to_read = self.determineLength(byte) byte += self.transport.read(to_read) length = self.decodeLength(byte) word = self.transport.read(length) return word.decode(encoding=self.encoding, errors='strict') def close(self): self.transport.close() librouteros-3.0.0/librouteros/query.py000066400000000000000000000026661356062631000201670ustar00rootroot00000000000000# -*- coding: UTF-8 -*- from itertools import chain from librouteros.protocol import ( cast_to_api, ) class Key: def __init__(self, name): self.name = name def __eq__(self, other): yield '?={}={}'.format(self, cast_to_api(other)) def __ne__(self, other): yield from self == other yield '?#!' def __lt__(self, other): yield '?<{}={}'.format(self, cast_to_api(other)) def __gt__(self, other): yield '?>{}={}'.format(self, cast_to_api(other)) def __str__(self): return str(self.name) class Query: def __init__(self, path, keys, api): self.path = path self.keys = keys self.api = api self.query = tuple() def where(self, *args): self.query = tuple(chain.from_iterable(args)) return self def __iter__(self): keys = ','.join(str(key) for key in self.keys) keys = '=.proplist={}'.format(keys) cmd = str(self.path.join('print')) return iter(self.api.rawCmd(cmd, keys, *self.query)) def And(left, right, *rest): #pylint: disable=invalid-name yield from left yield from right yield from chain.from_iterable(rest) yield '?#&' yield from ('?#&', ) * len(rest) def Or(left, right, *rest): #pylint: disable=invalid-name yield from left yield from right yield from chain.from_iterable(rest) yield '?#|' yield from ('?#|', ) * len(rest) librouteros-3.0.0/requirements.tests.txt000066400000000000000000000000651356062631000205130ustar00rootroot00000000000000pytest-xdist==1.* pytest==5.* pydocstyle yapf pylint librouteros-3.0.0/setup.cfg000066400000000000000000000007171356062631000157130ustar00rootroot00000000000000[tool:pytest] addopts = --strict -ra [yapf] based_on_style = pep8 spaces_before_comment = 4, 8 split_before_logical_operator = true align_closing_bracket_with_visual_indent = true blank_line_before_nested_class_or_def = true blank_lines_around_top_level_definition = 2 column_limit = 120 dedent_closing_brackets = true coalesce_brackets = false each_dict_entry_on_separate_line = true indent_dictionary_value = false split_arguments_when_comma_terminated = true librouteros-3.0.0/setup.py000077500000000000000000000027051356062631000156060ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import os from setuptools import setup here = os.path.dirname(__file__) def read(fname): """ Read given file's content. :param str fname: file name :returns: file contents :rtype: str """ return open(os.path.join(here, fname)).read() install_pkgs = ( ) setup_pkgs = ( 'setuptools>=12.0.5', ) setup( install_requires=install_pkgs, setup_requires=setup_pkgs, zip_safe=False, name='librouteros', version='3.0.0', description='Python implementation of MikroTik RouterOS API', long_description=read('README.rst'), author='Łukasz Kostka', author_email='lukasz.kostka@netng.pl', url='https://github.com/luqasz/librouteros', packages=['librouteros'], license='GNU GPLv2', keywords='mikrotik routeros api', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 'Operating System :: MacOS', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Software Development :: Libraries' ] ) librouteros-3.0.0/tests/000077500000000000000000000000001356062631000152275ustar00rootroot00000000000000librouteros-3.0.0/tests/integration/000077500000000000000000000000001356062631000175525ustar00rootroot00000000000000librouteros-3.0.0/tests/integration/conftest.py000066400000000000000000000052611356062631000217550ustar00rootroot00000000000000from time import sleep from os import ( devnull, environ, ) from random import randint from subprocess import Popen, check_call from tempfile import NamedTemporaryFile import socket import platform from pathlib import Path import pytest from librouteros import connect from librouteros.exceptions import LibRouterosError from librouteros.login import ( plain, token, ) DEV_NULL = open(devnull, 'w') VERSION_LOGIN = {'6.44.5': plain, '6.33.3': token} def api_session(port): last_exc = None for _ in range(30): try: return connect( host='127.0.0.1', port=port, username='admin', password='', ) except (LibRouterosError, socket.error, socket.timeout) as exc: last_exc = exc sleep(1) raise RuntimeError('Could not connect to device. Last exception {}'.format(last_exc)) def disk_image(version): """Create a temporary disk image backed by original one.""" img = NamedTemporaryFile() # Path to backing image must be absolute or relative to new image backing_img = Path().joinpath('images/routeros_{}.qcow2'.format(version)).absolute() cmd = [ 'qemu-img', 'create', '-f', 'qcow2', '-b', str(backing_img), img.name, ] check_call(cmd, stdout=DEV_NULL) return img def routeros_vm(disk_image): #pylint: disable=redefined-outer-name port = randint(49152, 65535) accel = { 'Darwin': 'hvf', 'Linux': 'kvm', } if environ.get('TRAVIS') and environ.get('CI'): accel['Linux'] = 'tcg' cmd = [ 'qemu-system-x86_64', '-m', '64', '-display', 'none', '-hda', disk_image.name, '-net', 'user,hostfwd=tcp::{}-:8728'.format(port), '-net', 'nic,model=virtio', '-cpu', 'max', '-accel', accel[platform.system()], ] proc = Popen(cmd, stdout=DEV_NULL, close_fds=True) return port, proc @pytest.fixture(scope='function', params=VERSION_LOGIN.keys()) def routeros_login(request): #pylint: disable=redefined-outer-name version = request.param image = disk_image(version) port, proc = routeros_vm(image) request.addfinalizer(proc.kill) request.addfinalizer(image.close) return port, VERSION_LOGIN[version] @pytest.fixture(scope='function') def routeros_api(request): #pylint: disable=redefined-outer-name version = '6.44.5' image = disk_image(version) port, proc = routeros_vm(image) request.addfinalizer(proc.kill) request.addfinalizer(image.close) return api_session(port=port) librouteros-3.0.0/tests/integration/test_general.py000066400000000000000000000036001356062631000225770ustar00rootroot00000000000000import socket from time import sleep from librouteros.query import Key from librouteros import connect from librouteros.exceptions import LibRouterosError def test_login(routeros_login): port, method = routeros_login api = None for _ in range(30): try: api = connect( host='127.0.0.1', port=port, username='admin', password='', login_method=method, ) break except (LibRouterosError, socket.error, socket.timeout): sleep(1) data = api('/system/identity/print') assert tuple(data)[0]['name'] == 'MikroTik' def test_query(routeros_api): new_address = '172.16.1.1/24' result = routeros_api( '/ip/address/add', address=new_address, interface='ether1', ) created_id = tuple(result)[0]['ret'] _id = Key('.id') address = Key('address') query = routeros_api.path('/ip/address').select(_id, address).where( _id == created_id, address == new_address, ) selected_data = tuple(query) assert len(selected_data) == 1 assert selected_data[0]['.id'] == created_id assert selected_data[0]['address'] == new_address def test_long_word(routeros_api): r""" Assert that when word length is encoded with \x00 in it, library should decode this without errors. Create a entry with long word length (256) resulting in word encoding of \x81\00. Check if when reading back, comment is same when set. """ long_value = 'a' * (256 - len('=comment=')) data = routeros_api( '/ip/address/add', address='172.16.1.1/24', interface='ether1', comment=long_value, ) _id = tuple(data)[0]['ret'] for row in routeros_api('/ip/address/print'): if row['.id'] == _id: assert row['comment'] == long_value librouteros-3.0.0/tests/integration/test_path.py000066400000000000000000000012021356062631000221120ustar00rootroot00000000000000from librouteros.query import Key def test_add_then_remove(routeros_api): ips = routeros_api.path('ip', 'address') new_id = ips.add(interface='ether1', address='192.168.1.1/24') ips.remove(new_id) _id = Key('.id') assert tuple() == tuple(ips.select(_id).where(_id == new_id)) def test_add_then_update(routeros_api): ips = routeros_api.path('ip', 'address') new_id = ips.add(interface='ether1', address='192.168.1.1/24') ips.update(**{'.id': new_id, 'address': '172.16.1.1/24'}) address = Key('address') assert tuple(ips.select(address).where(Key('.id') == new_id))[0]['address'] == '172.16.1.1/24' librouteros-3.0.0/tests/requirements/000077500000000000000000000000001356062631000177525ustar00rootroot00000000000000librouteros-3.0.0/tests/requirements/conftest.py000066400000000000000000000006311356062631000221510ustar00rootroot00000000000000import pytest from subprocess import check_output import sys @pytest.fixture def installed_packages(): pkgs = [] pip_executable = [sys.executable, '-m', 'pip'] result = check_output(pip_executable + ["freeze", "--local", "--all"]) for line in result.decode().splitlines(): if '==' in line: pkg, version = line.split('==', 1) pkgs.append(pkg) return pkgs librouteros-3.0.0/tests/unit/000077500000000000000000000000001356062631000162065ustar00rootroot00000000000000librouteros-3.0.0/tests/unit/conftest.py000066400000000000000000000030761356062631000204130ustar00rootroot00000000000000import pytest from collections import namedtuple from struct import pack WordLength = namedtuple('WordLength', ('integer', 'encoded')) WordPair = namedtuple('WordPair', ('word', 'pair')) @pytest.fixture(scope='function') def bad_length_bytes(): """len(length) must be < 5""" return b'\xff\xff\xff\xff\xff' @pytest.fixture(scope='function') def bad_length_int(): """Length must be < 268435456""" return 268435456 @pytest.fixture( scope='function', params=( WordLength(integer=0, encoded=b'\x00'), WordLength(integer=127, encoded=b'\x7f'), WordLength(integer=130, encoded=b'\x80\x82'), WordLength(integer=2097140, encoded=b'\xdf\xff\xf4'), WordLength(integer=268435440, encoded=b'\xef\xff\xff\xf0'), ) ) def valid_word_length(request): return request.param @pytest.fixture(scope='function', params=(pack('>B', i) for i in range(240, 256))) def bad_first_length_bytes(request): """First byte of length must be < 240.""" return request.param @pytest.fixture( params=( WordPair(word='=key=yes', pair=('key', True)), WordPair(word='=key=no', pair=('key', False)), WordPair(word='=key=string', pair=('key', 'string')), WordPair(word='=key=none', pair=('key', 'none')), WordPair(word='=key=22.2', pair=('key', '22.2')), WordPair(word='=key=22', pair=('key', 22)), WordPair(word='=key=0', pair=('key', 0)), ) ) def word_pair(request): """Words and key,value pairs used for casting from/to python/api in both directions.""" return request.param librouteros-3.0.0/tests/unit/test_api.py000066400000000000000000000026151356062631000203740ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import pytest from unittest.mock import MagicMock, patch from librouteros.api import ( Api, ) from librouteros.protocol import ( parse_word, compose_word, ApiProtocol, ) @pytest.mark.parametrize('word,pair', ( ('=dynamic=true', ('dynamic', True)), ('=dynamic=false', ('dynamic', False)), )) def test_bool_parse_word(word, pair): """ Test for parsing legacy bool values. Older routeros versions accept yes/true/no/false as values, but only return true/false. """ assert parse_word(word) == pair def test_parse_word(word_pair): assert parse_word(word_pair.word) == word_pair.pair def test_compose_word(word_pair): assert compose_word(*word_pair.pair) == word_pair.word class Test_Api: def setup(self): self.api = Api(protocol=MagicMock()) @patch.object(Api, 'readResponse') @patch.object(ApiProtocol, 'writeSentence') def test_rawCmd_calls_writeSentence(self, writeSentence_mock, read_mock): args = ('/command', '=arg1=1', '=arg2=2') self.api.rawCmd(*args) assert writeSentence_mock.called_once_with(*args) @patch.object(Api, 'readResponse', return_value=(1, 2)) @patch.object(ApiProtocol, 'writeSentence') def test_rawCmd_returns_from_readResponse(self, writeSentence_mock, read_mock): assert tuple(self.api.rawCmd('/command', '=arg1=1', '=arg2=2')) == (1, 2) librouteros-3.0.0/tests/unit/test_connections.py000066400000000000000000000043501356062631000221430ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import pytest from socket import error as SOCKET_ERROR, timeout as SOCKET_TIMEOUT, socket from unittest.mock import MagicMock, patch, call from librouteros.connections import SocketTransport from librouteros.exceptions import ( ProtocolError, FatalError, ConnectionClosed, ) class Test_SocketTransport: def setup(self): self.transport = SocketTransport(sock=MagicMock(spec=socket)) def test_calls_socket_close(self): self.transport.close() self.transport.sock.close.assert_called_once() def test_close_shutdown_exception(self): self.transport.sock.shutdown.side_effect = SOCKET_ERROR self.transport.close() self.transport.sock.close.assert_called_once_with() def test_close(self): self.transport.close() self.transport.sock.close.assert_called_once_with() def test_calls_sendall(self): self.transport.write(b'some message') self.transport.sock.sendall.assert_called_once_with(b'some message') @pytest.mark.parametrize("exception", (SOCKET_ERROR, SOCKET_TIMEOUT)) def test_write_raises_socket_errors(self, exception): self.transport.sock.sendall.side_effect = exception with pytest.raises(exception): self.transport.write(b'some data') def test_read_raises_when_recv_returns_empty_byte_string(self): self.transport.sock.recv.return_value = b'' with pytest.raises(ConnectionClosed): self.transport.read(3) def test_read_reads_full_length(self): """ Check if read() reads all data, even when socket.recv() needs to be called multiple times. """ self.transport.sock.recv.side_effect = (b'retu', b'rne', b'd') assert self.transport.read(8) == b'returned' # Check if we ask only for what is left after each recv() assert self.transport.sock.recv.call_args_list == [ call(8), call(4), call(1), ] @pytest.mark.parametrize("exception", (SOCKET_ERROR, SOCKET_TIMEOUT)) def test_recv_raises_socket_errors(self, exception): self.transport.sock.recv.side_effect = exception with pytest.raises(exception): self.transport.read(2) librouteros-3.0.0/tests/unit/test_exceptions.py000066400000000000000000000004071356062631000220010ustar00rootroot00000000000000# -*- coding: UTF-8 -*- from librouteros.exceptions import TrapError def test_TrapError_newlines(): r"""Assert that string representation replaces \r\n with comma.""" error = TrapError(message='some\r\n string') assert str(error) == 'some, string' librouteros-3.0.0/tests/unit/test_librouteros.py000066400000000000000000000041241356062631000221710ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import socket import pytest from unittest.mock import ( patch, Mock, ) from librouteros import ( DEFAULTS, Api, connect, create_transport, ) from librouteros.exceptions import TrapError from librouteros.login import ( encode_password, plain, ) def test_default_ssl_wrapper(): """Assert that wrapper returns same object as it was called with.""" assert DEFAULTS['ssl_wrapper'](int) is int @pytest.mark.parametrize( "key, value", ( ('timeout', 10), ('port', 8728), ('saddr', ''), ('subclass', Api), ('encoding', 'ASCII'), ('login_method', plain), ) ) def test_defaults(key, value): assert DEFAULTS[key] == value def test_default_keys(): assert set(DEFAULTS.keys()) == set( ( 'timeout', 'port', 'saddr', 'subclass', 'encoding', 'login_method', 'ssl_wrapper', ) ) def test_password_encoding(): result = encode_password('259e0bc05acd6f46926dc2f809ed1bba', 'test') assert result == '00c7fd865183a43a772dde231f6d0bff13' def test_non_ascii_password_encoding(): """Only ascii characters are allowed in password.""" with pytest.raises(UnicodeEncodeError): encode_password(token='259e0bc05acd6f46926dc2f809ed1bba', password=u'łą') @patch('librouteros.create_transport') def test_connect_raises_when_failed_login(transport_mock): failed = Mock(name='failed', side_effect=TrapError(message='failed to login')) with pytest.raises(TrapError): connect(host='127.0.0.1', username='admin', password='', login_method=failed) @pytest.mark.parametrize('exc', (socket.error, socket.timeout)) @patch('librouteros.create_connection') @patch('librouteros.SocketTransport') def test_create_connection_does_not_wrap_socket_exceptions(create_connection, transport, exc): kwargs = dict( host='127.0.0.1', port=22, timeout=2, saddr='', ) transport.side_effect = exc with pytest.raises(exc): create_transport(**kwargs) librouteros-3.0.0/tests/unit/test_path.py000066400000000000000000000052331356062631000205560ustar00rootroot00000000000000# -*- coding: UTF-8 -*- from unittest.mock import ( MagicMock, ) from librouteros.api import ( Api, Path, ) from librouteros.query import Query def test_api_path_returns_Path(): api = Api(protocol=MagicMock()) new = api.path('ip', 'address') assert new.path == '/ip/address' assert new.api == api assert isinstance(new, Path) class Test_Path: def setup(self): self.path = Path( path='/interface', api=MagicMock(), ) def test_path_str(self): assert str(self.path) == self.path.path def test_join_single_param(self): assert self.path.join('ethernet').path == self.path.path + '/ethernet' def test_join_multi_param(self): assert self.path.join('ethernet', 'print').path == self.path.path + '/ethernet/print' def test_join_rstrips_slash(self): assert self.path.join('ethernet', 'print/').path == self.path.path + '/ethernet/print' def test_select_returns_Query(self): new = self.path.select('disabled', 'name') assert type(new) == Query def test_select_Query_has_valid_attributes(self): new = self.path.select('disabled', 'name') assert new.api == self.path.api assert new.path == self.path assert new.keys == ('disabled', 'name') def test_remove(self): self.path.remove('*1', '*2', '*3') self.path.api.assert_called_once_with('/interface/remove', **{'.id': '*1,*2,*3'}) # Check if returned generator was consumed assert self.path.api.return_value.__iter__.call_count == 1 def test_add(self): self.path.api.return_value = ({'ret': '*1'}, ) new = {'interface': 'ether1', 'address': '172.1.1.1/24'} new_id = self.path.add(**new) self.path.api.assert_called_once_with('/interface/add', **new) assert new_id == '*1' def test_update(self): args = {'name': 'wan', '.id': '*1'} self.path.update(**args) self.path.api.assert_called_once_with('/interface/set', **args) # Check if returned generator was consumed assert self.path.api.return_value.__iter__.call_count == 1 def test_iter(self): items = ({'.id': '*1'}, {'.id': '*2'}) self.path.api.return_value = items new_items = tuple(self.path) assert new_items == items self.path.api.assert_called_once_with('/interface/print') def test_call(self): self.path.path = '/system/script' tuple(self.path('run')) self.path.api.assert_called_once_with('/system/script/run') # Check if returned generator was consumed assert self.path.api.return_value.__iter__.call_count == 1 librouteros-3.0.0/tests/unit/test_protocol.py000066400000000000000000000105261356062631000214640ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import pytest from socket import error as SOCKET_ERROR, timeout as SOCKET_TIMEOUT, socket from unittest.mock import MagicMock, patch, call from librouteros.protocol import ( Encoder, Decoder, ApiProtocol, ) from librouteros.connections import SocketTransport from librouteros.exceptions import ( ProtocolError, FatalError, ) class Test_Decoder: def setup(self): self.decoder = Decoder() self.decoder.encoding = 'ASCII' @pytest.mark.parametrize( "length,expected", ( (b'x', 0), # 120 (b'\xbf', 1), # 191 (b'\xdf', 2), # 223 (b'\xef', 3), # 239 ) ) def test_determineLength(self, length, expected): assert self.decoder.determineLength(length) == expected def test_determineLength_raises(self, bad_first_length_bytes): with pytest.raises(ProtocolError) as error: self.decoder.determineLength(bad_first_length_bytes) assert str(bad_first_length_bytes) in str(error.value) def test_decodeLength(self, valid_word_length): result = self.decoder.decodeLength(valid_word_length.encoded) assert result == valid_word_length.integer def test_decodeLength_raises(self, bad_length_bytes): with pytest.raises(ProtocolError) as error: self.decoder.decodeLength(bad_length_bytes) assert str(bad_length_bytes) in str(error.value) class Test_Encoder: def setup(self): self.encoder = Encoder() self.encoder.encoding = 'ASCII' def test_encodeLength(self, valid_word_length): result = self.encoder.encodeLength(valid_word_length.integer) assert result == valid_word_length.encoded def test_encodeLength_raises_if_lenghth_is_too_big(self, bad_length_int): with pytest.raises(ProtocolError) as error: self.encoder.encodeLength(bad_length_int) assert str(bad_length_int) in str(error.value) @patch.object(Encoder, 'encodeLength', return_value=b'len_') def test_encodeWord(self, encodeLength_mock): assert self.encoder.encodeWord('word') == b'len_word' assert encodeLength_mock.call_count == 1 def test_non_ASCII_word_encoding(self): """When encoding is ASCII, word may only contain ASCII characters.""" self.encoder.encoding = 'ASCII' with pytest.raises(UnicodeEncodeError): self.encoder.encodeWord(u'łą') def test_utf_8_word_encoding(self): """Assert that utf-8 encoding works.""" self.encoder.encoding = 'utf-8' assert self.encoder.encodeWord(u'łą').endswith(b'\xc5\x82\xc4\x85') @patch.object(Encoder, 'encodeWord', return_value=b'') def test_encodeSentence(self, encodeWord_mock): r""" Assert that: \x00 is appended to the sentence encodeWord is called == len(sentence) """ encoded = self.encoder.encodeSentence('first', 'second') assert encodeWord_mock.call_count == 2 assert encoded[-1:] == b'\x00' class Test_ApiProtocol: def setup(self): self.protocol = ApiProtocol( transport=MagicMock(spec=SocketTransport), encoding='ASCII', ) @patch.object(Encoder, 'encodeSentence') def test_writeSentence_calls_encodeSentence(self, encodeSentence_mock): self.protocol.writeSentence('/ip/address/print', '=key=value') encodeSentence_mock.assert_called_once_with('/ip/address/print', '=key=value') @patch.object(Encoder, 'encodeSentence') def test_writeSentence_calls_transport_write(self, encodeSentence_mock): """Assert that write is called with encoded sentence.""" self.protocol.writeSentence('/ip/address/print', '=key=value') self.protocol.transport.write.assert_called_once_with(encodeSentence_mock.return_value) @patch('librouteros.protocol.iter', return_value=('!fatal', 'reason')) def test_readSentence_raises_FatalError(self, iter_mock): """Assert that FatalError is raised with its reason.""" with pytest.raises(FatalError) as error: self.protocol.readSentence() assert str(error.value) == 'reason' assert self.protocol.transport.close.call_count == 1 def test_close(self): self.protocol.close() self.protocol.transport.close.assert_called_once_with() librouteros-3.0.0/tests/unit/test_query.py000066400000000000000000000045021356062631000207650ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import pytest from unittest.mock import (MagicMock, patch) from librouteros.query import ( Query, Key, And, Or, ) class Test_Query: def setup(self): self.query = Query( path=MagicMock(), api=MagicMock(), keys=MagicMock(), ) def test_after_init_query_is_empty_tuple(self): assert self.query.query == tuple() def test_where_returns_self(self): assert self.query.where() == self.query def test_where_chains_from_args(self): self.query.where((1, 2, 3), (4, 5)) assert self.query.query == (1, 2, 3, 4, 5) @patch('librouteros.query.iter') def test_iter_calls_api_rawCmd(self, iter_mock): self.query.keys = ('name', 'disabled') self.query.query = ('key1', 'key2') iter(self.query) self.query.api.rawCmd.assert_called_once_with( str(self.query.path.join.return_value), '=.proplist=name,disabled', 'key1', 'key2', ) class Test_Key: def setup(self): self.key = Key(name='key_name', ) @pytest.mark.parametrize('param, expected', ( (True, 'yes'), (False, 'no'), ('yes', 'yes'), (1, '1'), )) def test_eq(self, param, expected): result = tuple(self.key == param)[0] assert result == '?=key_name={}'.format(expected) def test_ne(self): assert tuple(self.key != 1) == ('?=key_name=1', '?#!') @pytest.mark.parametrize('param, expected', ( (True, 'yes'), (False, 'no'), ('yes', 'yes'), (1, '1'), )) def test_lt(self, param, expected): result = tuple(self.key < param)[0] assert result == '? param)[0] assert result == '?>key_name={}'.format(expected) def test_And(): assert tuple(And( (1, ), (2, ), (3, ), (4, ), )) == (1, 2, 3, 4, '?#&', '?#&', '?#&') def test_Or(): assert tuple(Or( (1, ), (2, ), (3, ), (4, ), )) == (1, 2, 3, 4, '?#|', '?#|', '?#|')