Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Friday, 13 June 2025

🚀 Building a High-Performance Python Syslog Server with Daily Log Rotation and Emergency Telegram Alerts

In this post, we’ll walk through building a high-performance, multi-threaded syslog server in Python that:

  • Listens on multiple UDP ports (like 514 and 1514)

  • Stores logs in daily-rotated SQLite databases

  • Detects critical syslog messages and sends real-time Telegram alerts

  • Handles tens of thousands of messages in queue without data loss

This system is ideal for network engineers and sysadmins managing OLTs, routers, or any syslog-capable devices.








🔧 What It Does

  • Accepts syslog messages over UDP

  • Stores them in a SQLite DB (separate file per day)

  • Creates per-device tables (based on source IP)

  • Triggers alerts for keywords like pon deregister, reset, rogue, etc.

  • Sends alerts to a Telegram group/bot

  • Uses Python’s threading and queue for concurrency and performance


🧠 Tech Stack

  • Python 3

  • socket for UDP communication

  • sqlite3 for local, fast storage

  • requests for Telegram alerts

  • threading and queue for parallel log handling


📦 Code Features

1. UDP Listener

Each port (514, 1514) runs in its own thread, decoding incoming messages and forwarding them into log_queue.

2. Queue-Based Log Writing

Log entries are pushed into log_queue (max 50,000). A separate log_writer thread reads from this queue and writes to SQLite in batches of 100 entries to optimize performance.

3. Daily Database Rotation

The log writer monitors the date and creates a new DB file per day:

When the date changes, the current DB connection is closed and a new one is opened automatically — no scheduler required.

4. Per-IP Table Creation

Logs are grouped into tables based on the device IP and date:

This avoids a massive flat table and speeds up filtering by device.

5. Real-time Telegram Alerts

When critical patterns are detected in the message content, an alert is pushed to alert_queue, which a separate thread sends to Telegram using:


🛡️ Keywords Triggering Alerts

These common OLT/network events are monitored:

  • "pon deregister"

  • "olt power up", "olt power down"

  • "reset", "reboot", "rogue"

  • "mac flapp", "loopback"

  • "device port updown" and others

You can customize or expand this list easily in the code.


🧪 Performance Tips

  • Use Queue(maxsize=50000) to buffer bursts of traffic

  • Process logs in batches to reduce DB writes

  • SO_RCVBUF of 16MB prevents dropped UDP packets

  • Use check_same_thread=False when accessing SQLite from threads

  • Separate alert and log writers prevent blocking


📂 Files Created

  • syslog_YYYYMMDD.db — one per day

  • Inside each DB: tables like logs_192_168_1_1_20250613

SQLite also creates temporary -wal and -shm files for performance, which is expected behavior.


🚀 Running the Server

Download

Donwload the server file and just click. It will run the server.

It starts:

  • UDP listeners on 514, 1514

  • Log writer and alert threads

  • Waits for Ctrl+C to shut down gracefully

Tuesday, 30 July 2024

Building a Simple Syslog Server with Python and Django: A Comprehensive Guide

In today's world, network monitoring and log management are essential for maintaining and troubleshooting network devices. If you're looking to build a reliable and customizable syslog server, Python and Django provide a powerful and flexible solution. This guide will walk you through creating a simple syslog server that not only captures logs but also supports exporting them to CSV with filters.





Introduction to the Syslog Server

A syslog server is crucial for collecting and managing logs from network devices. Our server is specifically designed to work seamlessly with MikroTik routers but is versatile enough to support other devices. This server captures log entries, processes them, and offers the ability to export filtered logs to CSV.

Key Features

  • Log Collection: Capture syslog messages from various network devices.
  • Auto Delete older than 30 days of data to faster performance
  • Filtering Options: Filter logs by host IP, message content, and specific timestamps.
  • Export to CSV: Easily export filtered logs to CSV for further analysis.

Setting Up the Syslog Server

1. Prerequisites

Before we dive into the implementation, make sure you have the following:

  • Python (3.x)
  • Django
  • Pandas, numpy, openpyxl library for CSV export
  • Basic understanding of Python and Django

Download the Syslog Server

You can download the complete code for this syslog server from the following link:

Drive link: Download


Instalation: 

Open your mikrotik and configure remote log first. My router ip 192.168.10.252. Run below command in your mikrotik. 

    /system logging action
    set 3 remote=192.168.0.104 src-address=192.168.10.113
    /system logging
    add action=remote topics=info

Download and extract the rar file. then open folder syslog_project. In project folder just run the following command with the server ip (which is your interface ip)

           python manage.py runserver 192.168.0.104:8000

It should run like below.




Now open browser and hit the link: http://192.168.0.104:8000/logs/

Conclusion

This guide provided a step-by-step approach to building a simple syslog server using Python and Django. The server captures logs, supports filtering by IP, message, and timestamp, and allows exporting the filtered data to CSV. This setup is especially useful for managing logs from MikroTik devices but can be adapted for other network devices as well.
Feel free to explore and modify the code to suit your specific requirements. Happy logging!



Friday, 17 May 2024

Introducing Our Comprehensive Vsol GPON OLT Support Portal || Network Automation

Managing and troubleshooting Optical Line Terminals (OLTs) and Optical Network Units (ONUs) can be a challenging task for any support or helpdesk team. That's why we are excited to introduce our fully automated OLT Support Portal, designed to simplify and streamline these processes.



Key Features of Our OLT Support Portal

Our OLT Support Portal is packed with features that enhance the efficiency and effectiveness of network management:

1. POP Information Management

  • Add, Update, and Delete POP Information: Users can easily manage Points of Presence (POP) information, ensuring that all network details are up-to-date and accurate.

2. OLT Management

  • Add, Update, and Delete OLTs: Seamlessly manage your OLTs with options to add new devices, update existing ones, or remove them from the network.
  • OLT Status Monitoring: Keep track of the operational status of all OLTs within the network, ensuring they are functioning optimally.
  • OLT Troubleshooting: Diagnose and resolve issues with OLTs quickly, minimizing downtime and improving network reliability.

3. ONU Management

  • ONU Status Monitoring: Check the status of ONUs to ensure they are connected and operating correctly.
  • ONU Reboot: Remotely reboot ONUs to resolve connectivity issues without the need for physical access.
  • ONU RX Power Check: Monitor the received optical power levels to ensure they are within acceptable ranges.
  • ONU VLAN Configuration: Configure VLANs on ONUs to maintain efficient and secure network segmentation.
  • ONU LAN Port Status: View the status of LAN ports on ONUs to ensure proper device connectivity.
  • ONU Learned MAC Check: Check the MAC addresses learned on ONU LAN ports to verify connected devices.
  • ONU Last Log: Access the latest logs from ONUs to troubleshoot and resolve issues effectively.

4. Customer Management

  • Add, Update, and Delete Customer Information: Manage customer details with ease, keeping your records accurate and up-to-date.

Benefits of Using Our Portal

  • Automation: Our portal automates many network management tasks, reducing the workload on your support team and minimizing human error.
  • Efficiency: With comprehensive features and easy-to-use interfaces, your team can resolve issues faster and with greater accuracy.
  • Reliability: Proactive monitoring and troubleshooting tools help maintain network stability and performance.
  • Scalability: Whether you manage a small network or a large one, our portal scales to meet your needs.

Conclusion

Our OLT Support Portal is a powerful tool designed to empower your helpdesk or support team. By simplifying the management and troubleshooting of OLTs and ONUs, it allows your team to focus on delivering exceptional service and maintaining a high-performing network. Try it out and experience the difference it can make in your network operations.

Friday, 10 May 2024

Vlan Extract from VSOL and CDATA Gpon OLT || OLT Automation with python

No Need anything to be install in your pc. Just download the exe file from given drive link. 

Download Link: Drive Link


Simply double click on it. Give ip, username and password. Then rest of the work will do python to extract all the vlan that are in your olt database. Demo Output given below





Give the username and password here. I have shown mine.




 Here's mine all the vlan id's that are in olt database is showing here with range also. If you found it help-full don't forget to share with other's

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



Building a Radius Server with Web GUI for Login Mikrotik Routers

  Building a Powerful RADIUS Server with FreeRADIUS and Django for MikroTik Devices If you're managing MikroTik routers and network acc...