Thursday, 18 April 2024

Mikrotik Automation With Python || Automate Everything


Tricky python script to get all the ip addresses with interface name that statically added in the mikrotik. 

Output:






Requirements:
    1. Python Version: Python 3.10.0
    2. Paramiko Package/Module:  Paramiko 3.4.0
    3. Pip Version: Pip 21.2.3

Download Python from python official page install: Python-3.10.0


While install don't forget to tick on Add to variable path



After install open cmd and run command verify python version

                    C:\Users\shaharul.islam>python --version
            Python 3.10.0

Then install paramiko package using below command:

        C:\Users\shaharul.islam> pip install paramiko


Create a new file with extension .py  mikrotik.py 

Paste below script and save. Google Drive Link : Mikrotik-SSH.py


import paramiko
import re


def ssh_connect(hostname, username, password):
    try:
        # Create SSH client
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # Connect to the SSH server
        ssh_client.connect(hostname, username=username, password=password,timeout=6) 
        # Return the SSH client object
        return ssh_client
    except paramiko.AuthenticationException as e:
        print("Authentication failed:", e)
    except paramiko.SSHException as e:
        print("SSH connection failed:", e)
    except paramiko.BadHostKeyException as e:
        print("Host key could not be verified:", e)
    except Exception as e:
        print("An error occurred:", e)
        # Handle other exceptions here
        # For example, network errors, connection timeout, etc.

def main():
    hostname = input("Enter Mikrotik Router IP: " )
    username = 'admin'
    password = ''

    mt_ssh = ssh_connect(hostname, username, password)
    if mt_ssh:
        #command here
        stdin, stdout, stderr = mt_ssh.exec_command('ip address export')

        # Regular expression pattern to match IP address, interface, and disable status
        ip_interface_pattern = r'add\s+address=(\d+\.\d+\.\d+\.\d+(/\d+)?\b)\s+(?:comment=\S+\s+)?(?:disabled=(\w+)\s+)?interface=(\S+)\s+(?:network=\d+\.\d+\.\d+\.\d+/\d+\s+)?'

        # Process each line of the command output
        for line in stdout:
            output_line = line.strip()
            
            # Skip lines that don't start with "add address"
            if not output_line.startswith("add address"):
                continue
            
            # Find matches in the current line
            match = re.match(ip_interface_pattern, output_line)
            
            # Print the result if a match is found
            if match:
                ip_address = match.group(1)
                disabled_status = match.group(3) if match.group(3) else "no"
                interface = match.group(4)
                print(f"IP Address: {ip_address}, Interface: {interface}, Disabled: {disabled_status}")
                mt_ssh.close()

if __name__ == "__main__":
    main()
    input("Press enter to close")


N.B: Python code is indent sensitive. So before every line of code ensure proper indent. Above code is perfectly described by given comment before line start. Router username and password predefined in code. 


Save and run it simply double click on the file.

Enter Mikrotik router ip address:


And the output is given below



Let's verify the ip addresses. I have already added some ip addresses before creating this script. After login router let's see ip addresses.



By Modifying above code can make power full script to make mikrotik automation. Here's just given an example. If you have big network with mikrotik. you can find which IP address used in which mikrotik simply modifying above script.

Also modifying above code you can done Specific task that need to create in multiple router. If this post found help full then don't forget to share with other's. Need help you can ask....



No comments:

Post a Comment

Thanks for your valuable feedback.

Comprehensive IP Calculator: Supporting Both IPv4 and IPv6

Download:  Download Whether you're a network engineer, IT professional, or simply a tech enthusiast, understanding IP addresses is cruci...