Created
January 30, 2023 01:58
-
-
Save riyas-rawther/0fecf8cbda5d34e9c030cbab66c22814 to your computer and use it in GitHub Desktop.
send an email alert when a port is down using python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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'] = '[email protected]' | |
msg['To'] = '[email protected]' | |
smtp_server = "smtp.gmail.com" | |
sender_email = "[email protected]" | |
receiver_email = "[email protected]" | |
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