diff --git a/library/mt_login_test.py b/library/mt_login_test.py index c3d1597..7197c5c 100644 --- a/library/mt_login_test.py +++ b/library/mt_login_test.py @@ -1,6 +1,5 @@ #! /usr/bin/python - -import json +import socket from ansible.module_utils import mt_api from ansible.module_utils.basic import AnsibleModule @@ -23,12 +22,19 @@ def main(): msg = "" mk = mt_api.Mikrotik(hostname,username,password) - try: - mk.login() - except: - module.fail_json( - msg="Could not log into Mikrotik device. Check the username and password." - ) + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + result = sock.connect_ex((hostname, 8728)) + if result == 0: + try: + mk.login() + except: + module.fail_json( + msg="Could not log into Mikrotik device. Check the username and password." + ) + else: + module.fail_json( + msg="Could not access RouterOS api." + " Verify API service is enabled and not blocked by firewall." + ) # response = apiros.talk([b'/ip/address/add', b'=address=192.168.15.2/24', b'=interface=ether7']) diff --git a/pythonlibs/mt_common.py b/pythonlibs/mt_common.py index bebd704..2a86ae6 100644 --- a/pythonlibs/mt_common.py +++ b/pythonlibs/mt_common.py @@ -2,6 +2,7 @@ from ansible.module_utils import mt_api import re import sys +import socket def list_to_string(list): @@ -83,12 +84,17 @@ class MikrotikIdempotent(): self.username, self.password, ) + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + result = sock.connect_ex((self.hostname, 8728)) + if result == 0: + try: + self.mk.login() + self.login_success = True + except: + self.failed_msg = "Could not log into Mikrotik device." + " Check the username and password.", + else: + self.failed_msg = "Could not access RouterOS api." + " Verify API service is enabled and not blocked by firewall.", - try: - self.mk.login() - self.login_success = True - except: - self.failed_msg = "Could not log into Mikrotik device." + " Check the username and password.", def get_current_params(self): clean_params(self.desired_params) diff --git a/tests/integration/tests.yml b/tests/integration/tests.yml index b978ee0..49ad40d 100644 --- a/tests/integration/tests.yml +++ b/tests/integration/tests.yml @@ -16,6 +16,7 @@ hostname: "{{ mt_hostname }}" username: "{{ mt_user }}" password: "{{ mt_pass }}" + tags: test_login ############################### # Interfaces