Friday, 19 April 2024

Fun with MikroTik using Python || Automate Everything

Fun with MikroTik put all commands and router's ip in a text file and run the script.


It's really boring work to do some specific same configuration that need to do in all the mikrotik. Like creating user, creating  queue, creating filter rules, mangle rules, address list adding, raw filter, ip pool, log configure, time zone, ntp etc much more. Individually need to login a mikrotik router via winbox/ssh/telnet.


Python gives us better solution. 

Demo given below and script Google drive download link:  Script Drive Link


Just download and install python version 3.10.0.  And install netmiko packege/module verision 4.3.0 using pip command. See python documentation or my previous blogpost.


Create a new folder name Mikrotik Automation.  inside folder create files like below





In command_file.txt please put all the command that you want to execute in all the mikrotik router. I have added some commands 

    1. ip pool
    2. PPPoE Profile
    3. Firewall mange rule
    4. Firewall Filter rule for invalid syn,fin,ack, Filter rule for drop Brute Force             Attack, port  scanner, ssh attack,  address list, 
    5. User Creation
    6. Ip services configure
    7. Log Configure
    8. Queue type and Simple Queue configure
    9. Clock, Time zone, Traffic-flow
    10. Graphing

Command_file.txt contains 91 of command that will execute like below



In the host_file.txt add all the mikrotik router loopback ip's.  I have added some ip address of my lab mikrotik router 



Almost Eleven router there i will automate the above configuration. In host_file contains like this.


In Fun-with-mikrotik.py file paste below code and save


from netmiko import ConnectHandler
import time
def main():
    username = input('Please Enter Username: ')
    password = input('Please Enter Password: ')
    # Define device parameters
    with open('host_file.txt', 'r') as file:
        host_addresses = file.readlines()
    
    # Read commands from the text file
    with open('command_file.txt', 'r') as file:
        commands = file.readlines()
    
    mikrotik = {
        'device_type': 'mikrotik_routeros',
        'username': username,
        'password': password,
    }
    
    # Establish SSH connection
    for host in host_addresses:
        mikrotik['host'] = host.strip()
        try:
            with open('log.txt', 'a') as log_file:  # Open log file in append mode
                with ConnectHandler(**mikrotik) as net_connect:
                    # Send commands to the router
                    output = net_connect.send_config_set(commands)
                    time.sleep(10)
                    print(f'Commands executed at: {host.strip()}')
                    log_file.write(f'Commands executed at: {host.strip()}\n')
        except Exception as e:
            with open('log.txt', 'a') as log_file:  # Open log file in append mode
                log_file.write(f'Error executing commands at: {host.strip()}\n')
                print("An error occurred:", e)
if __name__ == "__main__":
    main()
    input('Press enter to close.')


Double Click on the file to execute. And enter username and password of your mikrotik. Here mine is admin/admin




Just wait 2 minutes. And you will see the output like this. 



Don't worry those ip's are not reachable the script will notify you by loggin all the log in log.txt file. Contains all the log like below



If this blogpost found helpfull don't forget to share with other's. For any help can contact any time.

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....



Sunday, 7 April 2024

Wireguard VPN configure in mikrotik router os 7

 Wireguard VPN configure in mikrotik router os 7


First Create a wireguard logical interface

    /interface wireguard
  add listen-port=13231 mtu=1420 name=wireguard1

Or



Then add a ip address in wireguard interface.

    /ip address
   add address=10.10.10.1/24 interface=wireguard1 network=10.10.10.0


Or



Then as usual create masqurade or src-nat nat rule and DNS.

    /ip dns
    set servers=8.8.8.8
    /ip firewall nat
    add action=masquerade chain=srcnat
    

Now Create peer configuration

    /interface wireguard peers
    add allowed-address=10.10.10.2/32 interface=wireguard1 public-       key="Peer Public Key"





Now configure in wireguard client device and configure as below for android down from google play store and for windows : Download or visit https://www.wireguard.com/install/





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...