From aa0d682201b39813a9b3944403bc4f96cc109ac9 Mon Sep 17 00:00:00 2001 From: Antonio Espiritu Date: Thu, 2 Oct 2025 01:34:21 -0600 Subject: [PATCH] Commit inicial --- .gitignore | 5 +++ Dockerfile | 17 +++++++ docker-compose.yml | 10 +++++ ip.txt | 1 + requirements.txt | 2 + update copy.py | 54 +++++++++++++++++++++++ update.bat | 3 ++ update.py | 108 +++++++++++++++++++++++++++++++++++++++++++++ update.sh | 2 + urls.txt | 9 ++++ 10 files changed, 211 insertions(+) create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 docker-compose.yml create mode 100644 ip.txt create mode 100644 requirements.txt create mode 100644 update copy.py create mode 100644 update.bat create mode 100644 update.py create mode 100644 update.sh create mode 100644 urls.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d149da9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +# Ignorar archivo de variables de entorno +.env + +# Otros archivos de Python que no se deben subir +__pycache__/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..39fe6af --- /dev/null +++ b/Dockerfile @@ -0,0 +1,17 @@ +# 1. Usar una imagen base oficial de Python (ligera) +FROM python:3.11-slim + +# 2. Establecer el directorio de trabajo dentro del contenedor +WORKDIR /app + +# 3. Copiar el archivo de requerimientos primero para aprovechar el cache de Docker +COPY requirements.txt . + +# 4. Instalar las dependencias de Python +RUN pip install --no-cache-dir -r requirements.txt + +# 5. Copiar el resto del código de la aplicación al contenedor +COPY update.py . + +# 6. Comando por defecto para ejecutar el script cuando el contenedor inicie +CMD ["python", "update.py"] \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..5b8931e --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,10 @@ +version: '3.8' + +services: + web-checker: + build: . + container_name: web_checker_app + env_file: .env + restart: unless-stopped + volumes: + - ./urls.txt:/app/urls.txt \ No newline at end of file diff --git a/ip.txt b/ip.txt new file mode 100644 index 0000000..6862aac --- /dev/null +++ b/ip.txt @@ -0,0 +1 @@ +189.150.163.236 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..d44fe44 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +requests +python-dotenv \ No newline at end of file diff --git a/update copy.py b/update copy.py new file mode 100644 index 0000000..2c9b626 --- /dev/null +++ b/update copy.py @@ -0,0 +1,54 @@ +import requests +import time +import urllib.request +from datetime import datetime + + +while True: + try: + request = requests.get('https://www.google.com', timeout=5) + except (requests.ConnectionError, requests.Timeout): + print("Sin conexión a internet.") + else: + print("Con conexión a internet.") + + espe = requests.get('http://especialidades.diagnolab.org:3333') + aki = requests.get('https://akishino.diagnolab.org') + aki2 = requests.get('https://akishino2.diagnolab.org') + huix = requests.get('https://huixtla.diagnolab.org') + escu = requests.get('https://escuintla.diagnolab.org') + mxsig = requests.get('https://mxsig.com') + + print(espe) + if espe.status_code == 200: + print("correcto") + else: + print("alerta") + print(aki) + if aki.status_code == 200: + print("correcto") + else: + print("alerta") + print(aki2) + if aki2.status_code == 200: + print("correcto") + else: + print("alerta") + print(huix) + if huix.status_code == 200: + print("correcto") + else: + print("alerta") + print(escu) + if escu.status_code == 200: + print("correcto") + else: + print("alerta") + print(mxsig) + if mxsig.status_code == 200: + print("correcto") + else: + print("alerta") + + + time.sleep(60) diff --git a/update.bat b/update.bat new file mode 100644 index 0000000..7e2fd9d --- /dev/null +++ b/update.bat @@ -0,0 +1,3 @@ +timeout /t 1 /nobreak + +python update.py \ No newline at end of file diff --git a/update.py b/update.py new file mode 100644 index 0000000..51091d9 --- /dev/null +++ b/update.py @@ -0,0 +1,108 @@ +import requests +import time +import os +import smtplib +from email.message import EmailMessage +from dotenv import load_dotenv +from datetime import datetime + +# Cargar variables de entorno desde el archivo .env +load_dotenv() + +# --- Configuración de Notificaciones (Telegram) --- +TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") +TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID") + +# --- Configuración de Notificaciones (Email) --- +EMAIL_ADDRESS = os.getenv("EMAIL_ADDRESS") +EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD") +RECIPIENT_EMAIL = os.getenv("RECIPIENT_EMAIL") + +def send_email_notification(subject, body): + """Envía una notificación por correo electrónico usando Gmail.""" + if not all([EMAIL_ADDRESS, EMAIL_PASSWORD, RECIPIENT_EMAIL]): + print("Faltan credenciales de correo. No se enviará email.") + return + + msg = EmailMessage() + msg['Subject'] = subject + msg['From'] = EMAIL_ADDRESS + msg['To'] = RECIPIENT_EMAIL + msg.set_content(body) + + try: + with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: + smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) + smtp.send_message(msg) + print("Notificación por correo enviada.") + except Exception as e: + print(f"Error al enviar correo: {e}") + +def send_telegram_notification(message): + """Envía un mensaje a un chat de Telegram a través de un bot.""" + if not all([TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID]): + print("Faltan credenciales de Telegram. No se enviará notificación.") + return + api_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage" + try: + response = requests.post(api_url, json={'chat_id': TELEGRAM_CHAT_ID, 'text': message}) + response.raise_for_status() + print("Notificación de Telegram enviada.") + except requests.exceptions.RequestException as e: + print(f"Error al enviar notificación de Telegram: {e}") + + +while True: + current_hour = datetime.now().hour + + # El bucle se ejecuta solo entre las 7:00 AM y las 10:59 PM (22:59) + if 7 <= current_hour <= 22: + print(f"--- Iniciando verificación (Horario activo): {time.strftime('%Y-%m-%d %H:%M:%S')} ---") + try: + # Primero, verificamos la conexión a internet general + requests.get('https://www.google.com', timeout=5) + except (requests.ConnectionError, requests.Timeout): + print("Sin conexión a internet.") + else: + print("Con conexión a internet.") + + urls_a_verificar = [] + urls_file = 'urls.txt' + try: + with open(urls_file, 'r', encoding='utf-8') as f: + # Leemos cada línea, quitamos espacios en blanco y omitimos líneas vacías + urls_a_verificar = [line.strip() for line in f if line.strip()] + except FileNotFoundError: + print(f"🚨 Alerta: El archivo '{urls_file}' no fue encontrado. No se verificarán URLs.") + + if not urls_a_verificar: + print("No hay URLs en el archivo para verificar.") + + failed_sites = [] + + for url in urls_a_verificar: + try: + response = requests.get(url, timeout=10) + if response.ok: + print(f"✅ {url} -> Correcto (Status: {response.status_code})") + else: + error_message = f"Status: {response.status_code}" + print(f"🚨 {url} -> Alerta ({error_message})") + failed_sites.append((url, error_message)) + except (requests.ConnectionError, requests.Timeout) as e: + error_message = "Error de conexión/timeout" + print(f"🚨 {url} -> Alerta ({error_message})") + failed_sites.append((url, error_message)) + + if failed_sites: + summary_message = "🚨 ¡Alerta! Se detectaron fallos en los siguientes sitios:\n\n" + summary_message += "\n".join([f"- {site}: {reason}" for site, reason in failed_sites]) + + # Enviar notificaciones + send_telegram_notification(summary_message) + #send_email_notification("🚨 Alerta de Monitoreo: Sitios web con fallos", summary_message) + + time.sleep(600) # Espera 10 minutos para la siguiente verificación + else: + print(f"--- Fuera de horario ({time.strftime('%Y-%m-%d %H:%M:%S')}). El monitoreo se reanudará a las 7 AM. ---") + time.sleep(900) # Espera 15 minutos antes de volver a comprobar la hora diff --git a/update.sh b/update.sh new file mode 100644 index 0000000..f1d4f0c --- /dev/null +++ b/update.sh @@ -0,0 +1,2 @@ +cd "$(dirname "$0")" +exec python3 update.py diff --git a/urls.txt b/urls.txt new file mode 100644 index 0000000..f19c31c --- /dev/null +++ b/urls.txt @@ -0,0 +1,9 @@ +http://especialidades.diagnolab.org:3333 +https://akishino.diagnolab.org +https://akishino2.diagnolab.org +https://huixtla.diagnolab.org +https://cloud.diagnolab.org +https://diagnolab.org +https://mxsig.com +https://s1.jshtv.org +http://server.mxsig.com.mx:8096 \ No newline at end of file