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

78 lines
2.2 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
# FONCTION IMPORT URL FROM CSV + TEST REQUEST
def import_url():
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:
print(str(e))
#except:
#print('l\'url: ' + url + ' est invalide')
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 des sites HS: {mail} <br></h4>\n'.format(mail=mail)
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()
else:
print('Tout est OK ;)')
# MAIN (A)
urls = import_url()
send_mail(urls)
# PYTHON TIME (B)
# while True:
# urls = import_url()
# send_mail(urls)
# time.sleep(300)