import os import time import smtplib from email.mime.text import MIMEText def send_email_alert(ip_address): smtp_server = "mail.smtp2go.com" smtp_port = 587 smtp_username = "pinger" smtp_password = "Qix46X7aPhvIZwrk" sender_email = "pinger@pattinson.org" receiver_email = "james@pattinson.org" subject = "ALERT: EGFH gateway unreachable" body = f"The server with IP {ip_address} has been unreachable for over 5 minutes." msg = MIMEText(body) msg["Subject"] = subject msg["From"] = sender_email msg["To"] = receiver_email try: with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login(smtp_username, smtp_password) server.sendmail(sender_email, receiver_email, msg.as_string()) print("Alert email sent.") except Exception as e: print(f"Failed to send email: {e}") def ping_host(ip_address): response = os.system(f"ping -c 1 {ip_address} > /dev/null 2>&1") return response == 0 def monitor(ip_address, timeout=300, check_interval=10): downtime_start = None print(f"Starting monitor process on {ip_address}") while True: if ping_host(ip_address): downtime_start = None # Reset downtime if host is reachable else: if downtime_start is None: downtime_start = time.time() elif time.time() - downtime_start > timeout: send_email_alert(ip_address) downtime_start = None # Reset after sending email time.sleep(timeout) # Avoid spamming alerts time.sleep(check_interval) if __name__ == "__main__": monitor("192.168.24.1") # Replace with the actual IP