Here is some code that fixes the API timeout issue when trying to connect with self-signed certificates on the Mikrotik.
I have used this code and it works as expected.
#!/usr/bin/env python3
import ssl
import os
import socket
import re
from time import sleep
from datetime import datetime as dt
import pyinotify
import ujson
import json
import librouteros
from librouteros import connect
from librouteros.query import Key
import requests
# ... (earlier parts of the script remain unchanged)
def connect_to_tik():
global api
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE # Add this line
ctx.set_ciphers('DEFAULT@SECLEVEL=1') # Modified this line
while True:
try:
api = connect(username=USERNAME, password=PASSWORD, host=ROUTER_IP,
ssl_wrapper=ctx.wrap_socket, port=PORT)
print(f"[Mikrocata] Connected to Mikrotik")
break
except librouteros.exceptions.TrapError as e:
if "invalid user name or password" in str(e):
print("[Mikrocata] Invalid username or password.")
sleep(10)
continue
raise
except socket.timeout as e:
print(f"[Mikrocata] Socket timeout: {str(e)}.")
sleep(30)
continue
except ConnectionRefusedError:
print("[Mikrocata] Connection refused. (api-ssl disabled in router?)")
sleep(10)
continue
except OSError as e:
if e.errno == 113:
print("[Mikrocata] No route to host. Retrying in 10 seconds..")
sleep(10)
continue
if e.errno == 101:
print("[Mikrocata] Network is unreachable. Retrying in 10 seconds..")
sleep(10)
continue
raise
except ssl.SSLError as e:
print(f"[Mikrocata] SSL Error: {str(e)}. Retrying in 10 seconds..")
sleep(10)
continue
# ... (rest of the script remains unchanged)
Here is some code that fixes the API timeout issue when trying to connect with self-signed certificates on the Mikrotik.
I have used this code and it works as expected.