Compare commits

16 Commits

Author SHA1 Message Date
victor
ff9edd855e Added feature to save the state of the host 2024-05-05 00:26:48 +02:00
victor
76069b8193 Deleted Windows Lib 2024-05-04 22:30:35 +02:00
victor
aad6fb97a6 Añadido sistema de logs 2024-04-14 14:21:59 +02:00
victor
6ab6224ff6 deleted prints 2024-04-14 13:57:07 +02:00
victor
2b986eeabb dotenv no fuciona en RaspberryPi1 2024-04-14 13:50:22 +02:00
victor
90a7cb8581 dotenv no fuciona en RaspberryPi1 2024-04-14 13:48:26 +02:00
victor
7bccab9455 dotenv no fuciona en RaspberryPi1 2024-04-14 13:47:50 +02:00
03b7177ecf Merge pull request 'ReadIPs' (#1) from ReadIPs into main
Reviewed-on: #1
2024-04-14 13:29:40 +02:00
victor
807517be96 Added send_discord_message() 2024-04-14 13:24:09 +02:00
166067972e Changed main to define the structure of hosts and update 2024-04-08 23:52:03 +02:00
1aad27b937 Created toIP function and modified check_ping to work with ipaddress 2024-04-08 23:32:57 +02:00
2521b34df0 read_document function modified to just read the file and delete '\n' 2024-04-08 23:15:39 +02:00
69dd4bd1f4 Read IP document function created 2024-04-08 23:05:55 +02:00
87a3ee2886 Added function to ping a host 2024-04-07 14:24:43 +02:00
439a7d545e Added function to ping a host 2024-04-07 14:20:51 +02:00
victor
48f773f374 Added Try/except 2024-04-06 20:12:08 +02:00
3 changed files with 77 additions and 7 deletions

1
.env Normal file
View File

@@ -0,0 +1 @@
DISCORD_WEBHOOK_URL='https://discord.com/api/webhooks/1229025346385608824/kIt2dp2znu0jR85QbOPmoMAteHaB9BCJDTMfn0cHE9mwpxHkbUNc9By2Y7n6gpufoyco'

5
pyvenv.cfg Normal file
View File

@@ -0,0 +1,5 @@
home = C:\Users\vgall\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0
include-system-site-packages = false
version = 3.11.9
executable = C:\Users\vgall\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\python.exe
command = C:\Users\vgall\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\python.exe -m venv D:\Documentos\Status

View File

@@ -1,5 +1,16 @@
import argparse import argparse
import sys from pythonping import ping
import ipaddress
import requests
import logging
DISCORD_WEBHOOK_URL='https://discord.com/api/webhooks/1229025346385608824/kIt2dp2znu0jR85QbOPmoMAteHaB9BCJDTMfn0cHE9mwpxHkbUNc9By2Y7n6gpufoyco'
logging.basicConfig(filename='/var/log/status.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def read_document(document_name):
with open(document_name, 'r') as file:
# Leer todas las líneas del archivo y guardarlas en un conjunto
return {linea.rstrip('\n') for linea in file}
def parseArguments(): def parseArguments():
# Crear un objeto ArgumentParser # Crear un objeto ArgumentParser
@@ -11,11 +22,7 @@ def parseArguments():
try: try:
# Parsear los argumentos de la línea de comandos # Parsear los argumentos de la línea de comandos
args = parser.parse_args() return parser.parse_args()
if args.web:
return args.web
elif args.host:
return args.host
except argparse.ArgumentError as e: except argparse.ArgumentError as e:
# Si ocurre un error al analizar los argumentos, mostrar un mensaje de error # Si ocurre un error al analizar los argumentos, mostrar un mensaje de error
print("Error:", e) print("Error:", e)
@@ -23,7 +30,64 @@ def parseArguments():
parser.print_help() parser.print_help()
exit() exit()
def toIP(hosts):
ips = set()
for host in hosts:
try:
ip = ipaddress.IPv4Address(host)
ips.add(ip)
except ipaddress.AddressValueError:
print(f"La entrada '{host}' no es una dirección IP válida.")
return ips
def check_ping(hosts, fails):
for host in hosts:
try:
response = ping(str(host), count=4, timeout=2) # verbose=True -> Para ver la respuesta del ping
if not response.success():
logging.info(f"Bad ping: {host}")
if (host not in fails):
send_discord_message(f"Ping fallido para el host: {host}")
# Añadir el host a fails
fails.add(host)
elif response.success():
if host in fails:
fails.remove(host)
logging.info(f"Ping correct: {host}")
except Exception as e:
logging.info(f"Bad ping: {host}")
print(e)
print(fails)
save_status(fails)
def save_status(fails):
with open("failed.txt", "w") as file:
for fail in fails:
file.write(str(fail) + "\n")
file.close
def send_discord_message(message):
data = {
"content": message
}
try:
response = requests.post(DISCORD_WEBHOOK_URL, json=data)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Error sending Discord message: {e}")
logging.info(f"Error sending Discord message: {e}")
else:
logging.info("Discord message sent successfully!")
if __name__ == '__main__': if __name__ == '__main__':
args = parseArguments() args = parseArguments()
print(args) ips_and_hosts = set()
fails = set()
if args.host:
ips_and_hosts.update(toIP(read_document(args.host)))
fails.update(toIP(read_document("failed.txt")))
if args.web:
print("Hay webs")
# Parsear correctamente
# ips_and_hosts.update()
check_ping(ips_and_hosts, fails)