i will install this script in multi pc’s and every pc have different network and this script will check if devices (ip) are online or not , i want every pc’s to be upload the result to sftp server and one pc’s that have the principle option well aggregate all result from sftp and send them to me in email and slack notification
can some one help me with it
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import logging
import threading
import time
import requests
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
import paramiko
import subprocess
from collections import defaultdict
import platform
import socket
class DeviceMonitorApp:
def __init__(self, root):
self.root = root
self.root.title("Device Monitor")
self.config = {}
# Set up logging
logging.basicConfig(filename='device_monitor.log', level=logging.INFO, format='%(asctime)s - %(message)s')
# Create main frame
main_frame = ttk.Frame(root, padding="10")
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Slack Webhook URL Entry
ttk.Label(main_frame, text="Slack Webhook URL:").grid(row=0, column=0, padx=10, pady=5, sticky="e")
self.entry_webhook = ttk.Entry(main_frame, width=50)
self.entry_webhook.grid(row=0, column=1, padx=10, pady=5)
# Email Configuration
ttk.Label(main_frame, text="Email Configuration").grid(row=1, column=0, columnspan=2, pady=(15, 5), sticky="w")
ttk.Label(main_frame, text="SMTP Server:").grid(row=2, column=0, padx=10, pady=5, sticky="e")
self.entry_smtp_server = ttk.Entry(main_frame, width=50)
self.entry_smtp_server.grid(row=2, column=1, padx=10, pady=5)
ttk.Label(main_frame, text="SMTP Port:").grid(row=3, column=0, padx=10, pady=5, sticky="e")
self.entry_smtp_port = ttk.Entry(main_frame, width=50)
self.entry_smtp_port.grid(row=3, column=1, padx=10, pady=5)
ttk.Label(main_frame, text="Email Username:").grid(row=4, column=0, padx=10, pady=5, sticky="e")
self.entry_email_username = ttk.Entry(main_frame, width=50)
self.entry_email_username.grid(row=4, column=1, padx=10, pady=5)
ttk.Label(main_frame, text="Email Password:").grid(row=5, column=0, padx=10, pady=5, sticky="e")
self.entry_email_password = ttk.Entry(main_frame, show="*", width=50)
self.entry_email_password.grid(row=5, column=1, padx=10, pady=5)
ttk.Label(main_frame, text="Recipient Email:").grid(row=6, column=0, padx=10, pady=5, sticky="e")
self.entry_recipient_email = ttk.Entry(main_frame, width=50)
self.entry_recipient_email.grid(row=6, column=1, padx=10, pady=5)
# SFTP Configuration
ttk.Label(main_frame, text="SFTP Configuration").grid(row=7, column=0, columnspan=2, pady=(15, 5), sticky="w")
ttk.Label(main_frame, text="SFTP Host:").grid(row=8, column=0, padx=10, pady=5, sticky="e")
self.entry_sftp_host = ttk.Entry(main_frame, width=50)
self.entry_sftp_host.grid(row=8, column=1, padx=10, pady=5)
ttk.Label(main_frame, text="SFTP Port:").grid(row=9, column=0, padx=10, pady=5, sticky="e")
self.entry_sftp_port = ttk.Entry(main_frame, width=50)
self.entry_sftp_port.grid(row=9, column=1, padx=10, pady=5)
ttk.Label(main_frame, text="SFTP Username:").grid(row=10, column=0, padx=10, pady=5, sticky="e")
self.entry_sftp_username = ttk.Entry(main_frame, width=50)
self.entry_sftp_username.grid(row=10, column=1, padx=10, pady=5)
self.use_key_file = tk.BooleanVar(value=self.config.get("use_key_file", False))
self.checkbox_use_key_file = ttk.Checkbutton(main_frame, text="Use Key File for Authentication", variable=self.use_key_file, command=self.toggle_key_file)
self.checkbox_use_key_file.grid(row=11, column=1, padx=10, pady=5, sticky="w")
ttk.Label(main_frame, text="SFTP Key File:").grid(row=12, column=0, padx=10, pady=5, sticky="e")
self.entry_sftp_key_file = ttk.Entry(main_frame, width=50, state='normal' if self.use_key_file.get() else 'disabled')
self.entry_sftp_key_file.grid(row=12, column=1, padx=10, pady=5)
self.button_browse_key_file = ttk.Button(main_frame, text="Browse", command=self.browse_key_file, state='normal' if self.use_key_file.get() else 'disabled')
self.button_browse_key_file.grid(row=12, column=2, padx=10, pady=5)
ttk.Label(main_frame, text="SFTP Password:").grid(row=13, column=0, padx=10, pady=5, sticky="e")
self.entry_sftp_password = ttk.Entry(main_frame, show="*", width=50, state='disabled' if self.use_key_file.get() else 'normal')
self.entry_sftp_password.grid(row=13, column=1, padx=10, pady=5)
# Devices List Textbox
ttk.Label(main_frame, text="Devices (One per line):").grid(row=14, column=0, padx=10, pady=5, sticky="e")
self.text_devices = tk.Text(main_frame, width=50, height=10)
self.text_devices.grid(row=14, column=1, padx=10, pady=5)
# Check Interval Entry
ttk.Label(main_frame, text="Check Interval (seconds):").grid(row=15, column=0, padx=10, pady=5, sticky="e")
self.entry_interval = ttk.Entry(main_frame, width=10)
self.entry_interval.grid(row=15, column=1, padx=10, pady=5, sticky="w")
# Scheduler Options
ttk.Label(main_frame, text="Schedule Report").grid(row=16, column=0, columnspan=2, pady=(15, 5), sticky="w")
ttk.Label(main_frame, text="Schedule Interval (hours):").grid(row=17, column=0, padx=10, pady=5, sticky="e")
self.entry_schedule_interval = ttk.Entry(main_frame, width=10)
self.entry_schedule_interval.grid(row=17, column=1, padx=10, pady=5, sticky="w")
ttk.Label(main_frame, text="Specific Days (comma-separated, e.g., Mon,Wed,Fri):").grid(row=18, column=0, padx=10, pady=5, sticky="e")
self.entry_specific_days = ttk.Entry(main_frame, width=50)
self.entry_specific_days.grid(row=18, column=1, padx=10, pady=5, sticky="w")
# Buttons Frame
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=19, column=0, columnspan=2, pady=10)
# Save Configuration Button
self.btn_save_config = ttk.Button(button_frame, text="Save Configuration", command=self.save_config)
self.btn_save_config.grid(row=0, column=0, padx=5)
# Load Configuration Button
self.btn_load_config = ttk.Button(button_frame, text="Load Configuration", command=self.load_config)
self.btn_load_config.grid(row=0, column=1, padx=5)
# Start/Stop Monitoring Button
self.btn_start_stop = ttk.Button(button_frame, text="Start Monitoring", command=self.toggle_monitoring)
self.btn_start_stop.grid(row=0, column=2, padx=5)
# Test Button
self.btn_test = ttk.Button(button_frame, text="Test Now", command=self.test_now)
self.btn_test.grid(row=0, column=3, padx=5)
# Status Label
self.label_status = ttk.Label(main_frame, text="", wraplength=400)
self.label_status.grid(row=20, column=0, columnspan=2, pady=10)
self.monitoring = False
self.monitor_thread = None
self.device_statuses = defaultdict(list)
# Load configuration after initializing widgets
self.load_config()
def toggle_key_file(self):
if self.use_key_file.get():
self.entry_sftp_key_file.config(state='normal')
self.button_browse_key_file.config(state='normal')
self.entry_sftp_password.config(state='disabled')
else:
self.entry_sftp_key_file.config(state='disabled')
self.button_browse_key_file.config(state='disabled')
self.entry_sftp_password.config(state='normal')
def browse_key_file(self):
file_path = filedialog.askopenfilename()
if file_path:
self.entry_sftp_key_file.delete(0, tk.END)
self.entry_sftp_key_file.insert(0, file_path)
def save_config(self):
try:
check_interval = int(self.entry_interval.get()) if self.entry_interval.get() else 60
schedule_interval = int(self.entry_schedule_interval.get()) if self.entry_schedule_interval.get() else 24
specific_days = [day.strip() for day in self.entry_specific_days.get().split(',')] if self.entry_specific_days.get() else []
self.config = {
"webhook_url": self.entry_webhook.get(),
"smtp_server": self.entry_smtp_server.get(),
"smtp_port": self.entry_smtp_port.get(),
"email_username": self.entry_email_username.get(),
"email_password": self.entry_email_password.get(),
"recipient_email": self.entry_recipient_email.get(),
"sftp_host": self.entry_sftp_host.get(),
"sftp_port": self.entry_sftp_port.get(),
"sftp_username": self.entry_sftp_username.get(),
"use_key_file": self.use_key_file.get(),
"sftp_key_file": self.entry_sftp_key_file.get(),
"sftp_password": self.entry_sftp_password.get(),
"devices": self.text_devices.get("1.0", tk.END).strip().split("n"),
"check_interval": check_interval,
"schedule_interval": schedule_interval,
"specific_days": specific_days
}
with open('config.json', 'w') as config_file:
json.dump(self.config, config_file)
self.label_status.config(text="Configuration saved successfully.")
logging.info("Configuration saved successfully.")
except ValueError as e:
messagebox.showerror("Invalid Input", f"Error in configuration: {e}")
def load_config(self):
if os.path.exists('config.json'):
with open('config.json', 'r') as config_file:
self.config = json.load(config_file)
self.entry_webhook.delete(0, tk.END)
self.entry_webhook.insert(0, self.config.get("webhook_url", ""))
self.entry_smtp_server.delete(0, tk.END)
self.entry_smtp_server.insert(0, self.config.get("smtp_server", ""))
self.entry_smtp_port.delete(0, tk.END)
self.entry_smtp_port.insert(0, self.config.get("smtp_port", ""))
self.entry_email_username.delete(0, tk.END)
self.entry_email_username.insert(0, self.config.get("email_username", ""))
self.entry_email_password.delete(0, tk.END)
self.entry_email_password.insert(0, self.config.get("email_password", ""))
self.entry_recipient_email.delete(0, tk.END)
self.entry_recipient_email.insert(0, self.config.get("recipient_email", ""))
self.entry_sftp_host.delete(0, tk.END)
self.entry_sftp_host.insert(0, self.config.get("sftp_host", ""))
self.entry_sftp_port.delete(0, tk.END)
self.entry_sftp_port.insert(0, self.config.get("sftp_port", ""))
self.entry_sftp_username.delete(0, tk.END)
self.entry_sftp_username.insert(0, self.config.get("sftp_username", ""))
self.use_key_file.set(self.config.get("use_key_file", False))
self.toggle_key_file()
self.entry_sftp_key_file.delete(0, tk.END)
self.entry_sftp_key_file.insert(0, self.config.get("sftp_key_file", ""))
self.entry_sftp_password.delete(0, tk.END)
self.entry_sftp_password.insert(0, self.config.get("sftp_password", ""))
self.text_devices.delete("1.0", tk.END)
self.text_devices.insert("1.0", "n".join(self.config.get("devices", [])))
self.entry_interval.delete(0, tk.END)
self.entry_interval.insert(0, self.config.get("check_interval", ""))
self.entry_schedule_interval.delete(0, tk.END)
self.entry_schedule_interval.insert(0, self.config.get("schedule_interval", ""))
self.entry_specific_days.delete(0, tk.END)
self.entry_specific_days.insert(0, ",".join(self.config.get("specific_days", [])))
self.label_status.config(text="Configuration loaded successfully.")
logging.info("Configuration loaded successfully.")
def toggle_monitoring(self):
if self.monitoring:
self.monitoring = False
self.btn_start_stop.config(text="Start Monitoring")
self.label_status.config(text="Monitoring stopped.")
else:
self.save_config() # Save the configuration before starting
self.monitoring = True
self.btn_start_stop.config(text="Stop Monitoring")
self.label_status.config(text="Monitoring started.")
self.monitor_thread = threading.Thread(target=self.monitor_devices)
self.monitor_thread.daemon = True
self.monitor_thread.start()
def monitor_devices(self):
while self.monitoring:
self.check_devices()
interval = self.config.get("check_interval", 60)
for _ in range(interval):
if not self.monitoring:
break
time.sleep(1)
def check_devices(self):
self.device_statuses.clear()
devices = self.config.get("devices", [])
for device in devices:
status = self.ping_device(device)
self.device_statuses[device].append(status)
self.send_reports()
def ping_device(self, ip):
try:
param = '-n' if platform.system().lower() == 'windows' else '-c'
timeout = 1 # Set timeout to 1 second
result = subprocess.run(['ping', param, '1', '-w', str(timeout), ip], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return result.returncode == 0
except Exception as e:
logging.error(f"Error pinging {ip}: {e}")
return False
def send_reports(self):
message = "Device Status Reportnn"
for device, statuses in self.device_statuses.items():
status = "Online" if statuses[-1] else "Offline"
message += f"Device: {device}nStatus: {status}nn"
self.send_slack_notification(message)
self.send_email_notification(message)
self.upload_to_sftp(message) # Ensure the report is uploaded to SFTP
def send_slack_notification(self, message):
try:
hostname = socket.gethostname()
message = f"Hostname: {hostname}nn{message}"
webhook_url = self.config.get("webhook_url")
if webhook_url:
formatted_message = f"```{message}```"
payload = {"text": formatted_message}
requests.post(webhook_url, json=payload)
logging.info("Slack notification sent successfully.")
except Exception as e:
logging.error(f"Error sending Slack notification: {e}")
def send_email_notification(self, message):
try:
hostname = socket.gethostname()
message = f"Hostname: {hostname}nn{message}"
smtp_server = self.config.get("smtp_server")
smtp_port = self.config.get("smtp_port")
email_username = self.config.get("email_username")
email_password = self.config.get("email_password")
recipient_email = self.config.get("recipient_email")
if smtp_server and smtp_port and email_username and email_password and recipient_email:
msg = MIMEMultipart()
msg["From"] = email_username
msg["To"] = recipient_email
msg["Subject"] = "Device Status Report"
msg.attach(MIMEText(message, "plain"))
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(email_username, email_password)
server.sendmail(email_username, recipient_email, msg.as_string())
server.quit()
logging.info("Email notification sent successfully.")
except Exception as e:
logging.error(f"Error sending email notification: {e}")
def upload_to_sftp(self, device_status):
sftp_host = self.config.get("sftp_host")
sftp_port = int(self.config.get("sftp_port"))
sftp_username = self.config.get("sftp_username")
use_key_file = self.config.get("use_key_file", False)
sftp_key_file = self.config.get("sftp_key_file")
sftp_password = self.config.get("sftp_password")
try:
logging.info("Starting SFTP connection...")
transport = paramiko.Transport((sftp_host, sftp_port))
if use_key_file:
logging.info("Using key file for SFTP authentication...")
key = paramiko.RSAKey.from_private_key_file(sftp_key_file)
transport.connect(username=sftp_username, pkey=key)
else:
logging.info("Using password for SFTP authentication...")
transport.connect(username=sftp_username, password=sftp_password)
sftp = paramiko.SFTPClient.from_transport(transport)
logging.info("SFTP connection established successfully.")
try:
remote_file_path = "device_results.txt"
logging.info(f"Opening remote file {remote_file_path} for appending...")
hostname = socket.gethostname()
device_status_with_hostname = f"Hostname: {hostname}nn{device_status}"
logging.info(f"Device status being uploaded: {device_status_with_hostname}")
with sftp.file(remote_file_path, "a") as remote_file:
logging.info("Writing device status to remote file...")
remote_file.write(device_status_with_hostname + "nn")
logging.info("Device status uploaded to SFTP successfully.")
except Exception as file_error:
logging.error(f"Error writing to remote file: {file_error}")
finally:
logging.info("Closing SFTP connection...")
sftp.close()
transport.close()
except Exception as e:
logging.error(f"Error uploading to SFTP: {e}")
def test_now(self):
self.save_config() # Save the configuration before testing
self.check_devices()
if __name__ == "__main__":
root = tk.Tk()
app = DeviceMonitorApp(root)
root.mainloop()
New contributor
oussama harmas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.