Python Ip address monitoring tool (open source) written with help of AI and tested by me

All about AI
Post Reply
User avatar
david
Site Admin
Posts: 366
Joined: Sat May 21, 2016 7:50 pm

Python Ip address monitoring tool (open source) written with help of AI and tested by me

Post by david »

Python Ip address monitoring tool with alarm

Image

Code: Select all

import tkinter as tk
from tkinter import ttk
import threading
import subprocess
import os
import time
import winsound  # For Windows beep (remove for Linux)
                 # Linux alternative included in code

class PingMonitorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Ping Monitor")
        
        # Variables
        self.target_ip = tk.StringVar()
        self.interval = tk.StringVar(value="60")
        self.monitoring = False
        self.beep_active = False
        
        # GUI Layout
        ttk.Label(root, text="IP Address:").grid(row=0, column=0, padx=5, pady=5)
        self.ip_entry = ttk.Entry(root, textvariable=self.target_ip)
        self.ip_entry.grid(row=0, column=1, padx=5, pady=5)
        
        ttk.Label(root, text="Interval (seconds):").grid(row=1, column=0, padx=5, pady=5)
        self.interval_entry = ttk.Entry(root, textvariable=self.interval)
        self.interval_entry.grid(row=1, column=1, padx=5, pady=5)
        
        self.start_button = ttk.Button(root, text="Start Monitoring", command=self.toggle_monitoring)
        self.start_button.grid(row=2, column=0, columnspan=2, padx=5, pady=5)
        
        self.status_label = ttk.Label(root, text="Status: Stopped")
        self.status_label.grid(row=3, column=0, columnspan=2, padx=5, pady=5)
        
    def toggle_monitoring(self):
        if self.monitoring:
            self.stop_monitoring()
        else:
            self.start_monitoring()
    
    def start_monitoring(self):
        ip = self.target_ip.get()
        if not ip:
            self.update_status("Error: IP address required")
            return
        try:
            interval = int(self.interval.get())
        except ValueError:
            self.update_status("Error: Interval must be a number")
            return
            
        self.monitoring = True
        self.start_button.config(text="Stop Monitoring")
        self.update_status("Monitoring started...")
        
        # Start monitoring thread
        threading.Thread(target=self.monitor_loop, args=(ip, interval), daemon=True).start()
    
    def stop_monitoring(self):
        self.monitoring = False
        self.start_button.config(text="Start Monitoring")
        self.update_status("Monitoring stopped")
    
    def monitor_loop(self, ip, interval):
        while self.monitoring:
            if self.ping_ip(ip):
                self.beep_active = False
                self.update_status(f"{time.ctime()}: Ping successful to {ip}")
            else:
                self.beep_active = True
                self.update_status(f"{time.ctime()}: Ping failed to {ip}")
                # Start beep in separate thread
                threading.Thread(target=self.beep_loop, daemon=True).start()
            
            time.sleep(interval)
    
    def ping_ip(self, ip):
        try:
            output = subprocess.check_output(
                ['ping', '-c', '1', '-W', '5', ip],
                stderr=subprocess.STDOUT,
                universal_newlines=True
            )
            return True
        except subprocess.CalledProcessError:
            return False
    
    def beep_loop(self):
        while self.beep_active and self.monitoring:
            # For Linux (comment out if using Windows)
            os.system('echo -e "\a"')  # Terminal bell
            # For Windows (uncomment):
            # winsound.Beep(1000, 500)  # Frequency 1000Hz, duration 500ms
            time.sleep(1)
    
    def update_status(self, message):
        self.root.after(0, lambda: self.status_label.config(text=message))

if __name__ == "__main__":
    root = tk.Tk()
    app = PingMonitorApp(root)
    root.mainloop()


User avatar
david
Site Admin
Posts: 366
Joined: Sat May 21, 2016 7:50 pm

Re: Python Ip address monitoring tool (open source) generated by AI

Post by david »

Same ip monitoring tool but with telegram notifications:

1. You need to create a Telegram bot:

Open Telegram and search for @BotFather

Send /newbot and follow instructions

2. Get the API token (looks like 1234567890:ABCdefGhIJKlmNoPQRsTUVwxyZ)

Get your Chat ID:

Search for @userinfobot in Telegram and click "Start"

It will reply with your chat ID (a number like 123456789)


Code: Select all

import tkinter as tk
from tkinter import ttk
import threading
import subprocess
import os
import time
import requests

class PingMonitorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Ping Monitor")
        
        # Variables
        self.target_ip = tk.StringVar()
        self.interval = tk.StringVar(value="60")
        self.bot_token = tk.StringVar()
        self.chat_id = tk.StringVar()
        self.monitoring = False
        self.beep_active = False
        
        # GUI Layout
        ttk.Label(root, text="IP Address:").grid(row=0, column=0, padx=5, pady=5)
        self.ip_entry = ttk.Entry(root, textvariable=self.target_ip)
        self.ip_entry.grid(row=0, column=1, padx=5, pady=5)
        
        ttk.Label(root, text="Interval (seconds):").grid(row=1, column=0, padx=5, pady=5)
        self.interval_entry = ttk.Entry(root, textvariable=self.interval)
        self.interval_entry.grid(row=1, column=1, padx=5, pady=5)
        
        ttk.Label(root, text="Telegram Bot Token:").grid(row=2, column=0, padx=5, pady=5)
        self.bot_token_entry = ttk.Entry(root, textvariable=self.bot_token)
        self.bot_token_entry.grid(row=2, column=1, padx=5, pady=5)
        
        ttk.Label(root, text="Telegram Chat ID:").grid(row=3, column=0, padx=5, pady=5)
        self.chat_id_entry = ttk.Entry(root, textvariable=self.chat_id)
        self.chat_id_entry.grid(row=3, column=1, padx=5, pady=5)
        
        self.start_button = ttk.Button(root, text="Start Monitoring", command=self.toggle_monitoring)
        self.start_button.grid(row=4, column=0, columnspan=2, padx=5, pady=5)
        
        self.status_label = ttk.Label(root, text="Status: Stopped")
        self.status_label.grid(row=5, column=0, columnspan=2, padx=5, pady=5)
        
    def toggle_monitoring(self):
        if self.monitoring:
            self.stop_monitoring()
        else:
            self.start_monitoring()
    
    def start_monitoring(self):
        ip = self.target_ip.get()
        if not ip:
            self.update_status("Error: IP address required")
            return
        try:
            interval = int(self.interval.get())
        except ValueError:
            self.update_status("Error: Interval must be a number")
            return
            
        self.monitoring = True
        self.start_button.config(text="Stop Monitoring")
        self.update_status("Monitoring started...")
        
        # Start monitoring thread
        threading.Thread(target=self.monitor_loop, args=(ip, interval), daemon=True).start()
    
    def stop_monitoring(self):
        self.monitoring = False
        self.start_button.config(text="Start Monitoring")
        self.update_status("Monitoring stopped")
    
    def monitor_loop(self, ip, interval):
        first_failure = True  # To send notification only on first failure
        while self.monitoring:
            if self.ping_ip(ip):
                self.beep_active = False
                self.update_status(f"{time.ctime()}: Ping successful to {ip}")
                first_failure = True  # Reset for next failure cycle
            else:
                self.beep_active = True
                self.update_status(f"{time.ctime()}: Ping failed to {ip}")
                
                # Send Telegram notification only on first failure
                if first_failure:
                    self.send_telegram_alert(f"🚨 Ping failed to {ip}")
                    first_failure = False
                
                # Start beep in separate thread
                threading.Thread(target=self.beep_loop, daemon=True).start()
            
            time.sleep(interval)
    
    def ping_ip(self, ip):
        try:
            output = subprocess.check_output(
                ['ping', '-c', '1', '-W', '5', ip],
                stderr=subprocess.STDOUT,
                universal_newlines=True
            )
            return True
        except subprocess.CalledProcessError:
            return False
    
    def send_telegram_alert(self, message):
        bot_token = self.bot_token.get()
        chat_id = self.chat_id.get()
        
        if not bot_token or not chat_id:
            return  # Skip if Telegram credentials not provided
        
        url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
        params = {
            'chat_id': chat_id,
            'text': message
        }
        
        try:
            response = requests.post(url, params=params)
            response.raise_for_status()
        except Exception as e:
            self.update_status(f"Telegram error: {str(e)}")
    
    def beep_loop(self):
        while self.beep_active and self.monitoring:
            # Linux beep
            os.system('echo -e "\a"')
            time.sleep(1)
    
    def update_status(self, message):
        self.root.after(0, lambda: self.status_label.config(text=message))

if __name__ == "__main__":
    root = tk.Tk()
    app = PingMonitorApp(root)
    root.mainloop()

New features added:

1.Telegram bot token and chat ID input fields

2.Alert notification sent on first failure detection

3.Non-blocking Telegram message sending

4.Error handling for Telegram API calls

How to use the Telegram integration:

1.Install Python lib package:

Code: Select all

pip install requests
2.Fill in your Telegram bot token and chat ID in the GUI

3.When ping fails for the first time, it will:

- Send a Telegram message
- Start beeping

4. It will only send one notification per failure cycle (stops spamming)

The notification will look like this in Telegram:

Code: Select all

Ping failed to 192.168.1.1
The script will continue beeping and monitoring until you either:

- Click "Stop Monitoring"

- Close the program

- The connection is restored

Note: The Telegram notification is only sent on the first failure detection to avoid spamming. If you want continuous notifications, remove the first_failure logic in the monitor_loop function.


Post Reply