Python script to alert in case of site down
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
python-stack-alert/python-alert.py

111 lines
3.0 KiB

2 years ago
# IMPORTS
import smtplib, ssl, sys, requests, csv, time
sys.path.append("./env.py")
from env import serveurMailPassword, serveurPort, serveurSmtp, serveurAdrresseMail, mailReception
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
is_in_alert = False
time_limit = 100 # POUR LE TEMPS ENTRE CHAQUES MAILS UNE FOIS L'ALERTE DÉCLENCHÉE UNE PREMIÈRE FOIS
2 years ago
# FONCTION IMPORT URL FROM CSV + TEST REQUEST
def test_url():
2 years ago
print(time.ctime())
urls_hs = []
with open('./url.csv', newline='') as file:
reader = csv.reader(file)
for row in reader:
addr = str(row)
url = addr.strip('[]')
try:
response = requests.get(url.strip('"\''))
if response.status_code != 200:
urls_hs.append(url)
print(url + ' est hors service')
else:
print(url + ' / ' + str(response.status_code))
except Exception as e:
urls_hs.append(url)
2 years ago
print(str(e))
return urls_hs
# FONCTION SEND MAIL
def send_mail(urls_hs):
# EN-TETE EMAIL
message = MIMEMultipart('mixed')
message['From'] = serveurAdrresseMail
message['To'] = mailReception
message['CC'] = ''
message['Subject'] = 'Attention, un ou plusieurs site(s) semble(nt) hors service'
# CONTENU (TEXT)
if urls_hs:
for url in urls_hs:
mail = " ".join(urls_hs)
contenu = '<h4>Bonjour, voici la liste du ou des sites HS: {mail} <br></h4>\n'.format(mail=mail)
2 years ago
body = MIMEText(contenu, 'html')
message.attach(body)
# CONVERSION EN CHAINE DE CARACTERES
mail_str = message.as_string()
context = ssl.create_default_context()
# ENVOIE DU MAIL
with smtplib.SMTP_SSL(serveurSmtp, serveurPort, context=context) as server:
server.login(serveurAdrresseMail, serveurMailPassword)
server.sendmail(serveurAdrresseMail,
mailReception,
mail_str)
server.quit()
# ALERTE = TRUE
is_in_alert = True
time_stamp = time.ctime()
2 years ago
else:
print('Tout est OK ;)')
is_in_alert = False
print(is_in_alert)
# CHECK TIMER FONCTIONS
def check_timer(time_stamp, current_time):
if current_time - time_stamp > time_limit:
print(current_time - time_stamp)
resend = True
else:
resend = False
print(current_time - time_stamp)
return resend
# FONCTION CHECK IF MAIL ALREADY SEND
def check_alert():
if is_in_alert:
# CHECK si timer > 1 heure
resend = check_timer(time_stamp, time.ctime())
if resend:
urls = test_url()
send_mail(urls)
else:
urls = test_url()
send_mail(urls)
2 years ago
# MAIN (A)
check_alert()
2 years ago
# PYTHON TIME (B)
# while True:
# urls = test_url()
2 years ago
# send_mail(urls)
# time.sleep(300)