commit fcfe78c2c1a00c244b39168c75a4af40654fc74f Author: greglebreton Date: Mon Nov 21 11:05:50 2022 +0100 push diff --git a/README.md b/README.md new file mode 100644 index 0000000..4b13831 --- /dev/null +++ b/README.md @@ -0,0 +1,74 @@ +# PYTHON ALERT FOR DOWNED SITES + +## PRE-REQUIS + +- Python3 +- time, requests, csv + +```bash +python3 -m pip install -r requirements +``` + +## INSTALLATION + +```bash +sudo mkdir /workspace +sudo chown "$(whoami)":"$(whoami)" /workspace && cd /workspace +git clone https://gitlab.com/GregLebreton/python-alert-stack.git +cd python-alert-stack +mkdir logs +``` + +## CONFIGURATION + +### WITH CRON (A) + +- Tâche CRON éxécutant les script toutes les 5 minutes: +```bash +crontab -e +*/5 * * * * /usr/bin/python3 /workspace/python-alert-stack/python-alert.py >> /workspace/python-alert-stack/logs/python-alert.log +``` + +### WITH PYTHON TIME FUNCTION (B) + +```bash +sudo nano /etc/systemd/system/python-alert-downsite.service +[Unit] +Description=Python Alert For Down Sites +[Service] +# Note: setting PYTHONUNBUFFERED is necessary to see the output of this service in the jo> +# See https://docs.python.org/2/using/cmdline.html#envvar-PYTHONUNBUFFERED +Environment=PYTHONUNBUFFERED=true + +ExecStart=/usr/bin/python3 /workspace/python-alert-stack/python-alert.py + +Type=oneshot +#WatchdogSec=30 +Restart=on-failure +RestartSec=10 + +[Install] +WantedBy=multi-user.target +``` + +> Note: Modifier la fin du python-alert.py script comme ceci: +```bash +# MAIN (A) +#urls = import_url() +#send_mail(urls) + +# PYTHON TIME (B) +while True: + urls = import_url() + send_mail(urls) +# temps d'attente entre chaque éxécutions du check (en secondes) + time.sleep(300) +``` + +### LOGS SENDER + +- Tâche CRON éxécutant le script une fois par semaine (Lundi à 10h00): +```bash +crontab -e +00 10 * * mon /usr/bin/python3 /workspace/python-alert-stack/logs-sender.py +``` \ No newline at end of file diff --git a/destinataires.csv b/destinataires.csv new file mode 100644 index 0000000..5d9bf3c --- /dev/null +++ b/destinataires.csv @@ -0,0 +1,2 @@ +mail1@mail.com +mail2@mail.com diff --git a/env.py b/env.py new file mode 100644 index 0000000..133410a --- /dev/null +++ b/env.py @@ -0,0 +1,5 @@ +serveurSmtp = "" +serveurPort = 465 +serveurAdrresseMail= "" +serveurMailPassword = "" +mailReception= "" diff --git a/logs-sender.py b/logs-sender.py new file mode 100644 index 0000000..06b6b58 --- /dev/null +++ b/logs-sender.py @@ -0,0 +1,81 @@ +import smtplib, ssl, sys, requests, csv, time, zipfile, os, env +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 ZIP +def zip_it(): + zip = zipfile.ZipFile('./logs/stack-alert-logs.zip', mode='w') + zip.write('./logs/python-alert.log') + zip.close() + +# FONCTION IMPORT URL FROM CSV + TEST REQUEST +def import_mails(): + + print(time.ctime()) + mails = [] + with open('./autres-destinataires.csv', newline='') as file: + reader = csv.reader(file) + for row in reader: + # NETTOYAGE + addr = str(row) + mailraw = addr.strip('[]\'') + mails.append(mailraw) + + return mails + +# FONCTION CLEAN OLD LOGS +def clean_logs(): + if os.path.exists('./logs/python-alert.log'): + os.remove('/./logs/python-alert.log') + if os.path.exists('/./logs/stack-alert-logs.zip'): + os.remove('./logs/stack-alert-logs.zip') + +# FONCTION SEND MAIL +def send_mail(mails): + + # EN-TETE EMAIL + message = MIMEMultipart('mixed') + message['From'] = serveurAdrresseMail + message['To'] = mailReception + message['CC'] = ",".join(mails) + message['Subject'] = 'Rapport hebdo sites HS' + + # CONTENU (TEXT) + contenu = '

Bonjour, voici logs des sites HS de la semaine

\n' + + body = MIMEText(contenu, 'html') + message.attach(body) + + # AJOUT PIECE JOINTE + attachmentPath = "/workspace/python-alert-stack/logs/stack-alert-logs.zip" + + try: + with open(attachmentPath, "rb") as attachment: + p = MIMEApplication(attachment.read(),_subtype="zip") + p.add_header('Content-Disposition', "attachment; filename= %s" % attachmentPath.split("\\")[-1]) + message.attach(p) + except Exception as e: + print(str(e)) + + # 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, + mails, + mail_str) + server.quit() + +# MAIN +mails = import_mails() +zip_it() +send_mail(mails) +clean_logs() \ No newline at end of file diff --git a/python-alert.py b/python-alert.py new file mode 100755 index 0000000..739ea79 --- /dev/null +++ b/python-alert.py @@ -0,0 +1,77 @@ +# 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 = '

Bonjour, voici la liste des sites HS: {mail}

\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) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..ffe6139 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +requests +csv>=0.1 +time>=0.1 \ No newline at end of file diff --git a/url.csv b/url.csv new file mode 100644 index 0000000..7fe2c96 --- /dev/null +++ b/url.csv @@ -0,0 +1,9 @@ +https://www.gregandev.fr +https://www.wordpress.gregandev.fr +https://medias.gregandev.fr +https://grego.gregandev.fr +https://retroarch.gregandev.fr +https://hugo.gregandev.fr +https://gregstation.gregandev.fr +https://psychologue-ecouen.fr +https://www.terminal-cv.gregandev.fr \ No newline at end of file