Skip to content

Instantly share code, notes, and snippets.

@riyas-rawther
Created January 30, 2023 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riyas-rawther/0fecf8cbda5d34e9c030cbab66c22814 to your computer and use it in GitHub Desktop.
Save riyas-rawther/0fecf8cbda5d34e9c030cbab66c22814 to your computer and use it in GitHub Desktop.
send an email alert when a port is down using python3
#!/bin/python3
import smtplib, ssl, socket
from email.mime.text import MIMEText
port = 465 # For SSL
msg = MIMEText('Sensu is Down!. Please do the needful')
msg['Subject'] = 'Sensu is down!'
msg['From'] = 'noreply.xxxx@gmail.com'
msg['To'] = 'riyas.rawther@xxxx.com'
smtp_server = "smtp.gmail.com"
sender_email = "noreply.xxxx@gmail.com"
receiver_email = "riyas.rawther@xxxx.com"
password = "utkvftkarcakxrwj"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1',3000))
# where 3000 is the port to be monitored
def send_email():
print ("sending email")
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg.as_string())
if result == 0:
print ("Port is open")
else:
print ("Port is not open")
send_email()
sock.close()
# add a crontab
# * * * * * /bin/python3 /usr/src/send-alert-if-sensu-docker-is-down.py > /usr/src/cron-sensu.log
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment