How can I create a Python script to ping multiple IP addresses and send email notifications to multiple recipients when any of the IPs are down?

rafiqul
Rafiqul Hasan
Published on May, 15 2024 1 min read 0 comments
image
import subprocess
import platform
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def ping_host(ip):
   # Determine the appropriate ping command based on the platform
   if platform.system().lower() == "windows":
       command = ['ping', '-n', '1', ip]  # Windows syntax
   else:
       command = ['ping', '-c', '1', ip]  # Unix-like syntax
   
   try:
       subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
       return True  # If the ping is successful, return True
   except subprocess.CalledProcessError:
       return False  # If the ping fails, return False

def send_email(subject, body, receiver_emails):
   sender_email = "[email protected]"
   password = "**********"

   message = MIMEMultipart()
   message["From"] = sender_email
   message["To"] = ", ".join(receiver_emails)  # Join receiver emails with comma
   message["Subject"] = subject

   message.attach(MIMEText(body, "plain"))

   with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
       server.login(sender_email, password)
       server.sendmail(sender_email, receiver_emails, message.as_string())

def main():
   # List of IP addresses to ping
   ip_addresses = ['36.255.68.153', '36.255.68.111', '36.255.71.132']
   
   # List of receiver email addresses
   receiver_emails = ["[email protected]", "[email protected]"]

   # Ping each IP address and print whether it's up or down
   for ip in ip_addresses:
       if ping_host(ip):
           print(f'{ip} is UP')
       else:
           print(f'{ip} is DOWN')
           subject = f'Alert: {ip} is DOWN'
           body = f'The IP address {ip} is not reachable.'
           send_email(subject, body, receiver_emails)
           

if __name__ == "__main__":
   main()

 

my code is above. sometimes it gives correcrt and sometimes it gives incorrect results. 

0 Answers