From 69dd4bd1f461e56aa88dc7d182ef60535851651b Mon Sep 17 00:00:00 2001 From: vgallegoiz Date: Mon, 8 Apr 2024 23:05:55 +0200 Subject: [PATCH 01/10] Read IP document function created --- status.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/status.py b/status.py index c5b1d64..29ba4f4 100644 --- a/status.py +++ b/status.py @@ -1,6 +1,22 @@ import argparse from pythonping import ping +import ipaddress +def read_document(document_name): + with open(document_name, 'r') as file: + # Leer todas las líneas del archivo y guardarlas en un conjunto + lines = file.readlines() + ips = set() + for line in lines: + # Eliminar caracteres de nueva línea y espacios en blanco alrededor + line = line.strip() + # Convertir la línea a un objeto IPv4Address + try: + ip = ipaddress.IPv4Address(line) + ips.add(ip) + except ipaddress.AddressValueError: + print(f"La entrada '{line}' no es una dirección IP válida.") + return ips def parseArguments(): # Crear un objeto ArgumentParser From 2521b34df097be01817f08a10a7cded667cf662a Mon Sep 17 00:00:00 2001 From: vgallegoiz Date: Mon, 8 Apr 2024 23:15:39 +0200 Subject: [PATCH 02/10] read_document function modified to just read the file and delete '\n' --- status.py | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/status.py b/status.py index 29ba4f4..0ff9d96 100644 --- a/status.py +++ b/status.py @@ -5,18 +5,7 @@ import ipaddress def read_document(document_name): with open(document_name, 'r') as file: # Leer todas las líneas del archivo y guardarlas en un conjunto - lines = file.readlines() - ips = set() - for line in lines: - # Eliminar caracteres de nueva línea y espacios en blanco alrededor - line = line.strip() - # Convertir la línea a un objeto IPv4Address - try: - ip = ipaddress.IPv4Address(line) - ips.add(ip) - except ipaddress.AddressValueError: - print(f"La entrada '{line}' no es una dirección IP válida.") - return ips + return {linea.rstrip('\n') for linea in file} def parseArguments(): # Crear un objeto ArgumentParser @@ -29,10 +18,12 @@ def parseArguments(): try: # Parsear los argumentos de la línea de comandos args = parser.parse_args() - if args.web: - return args.web + if args.web and args.host: + return args.host, args.web elif args.host: return args.host + elif args.web: + return args.web except argparse.ArgumentError as e: # Si ocurre un error al analizar los argumentos, mostrar un mensaje de error print("Error:", e) @@ -51,4 +42,3 @@ def check_ping(host): if __name__ == '__main__': args = parseArguments() - print(check_ping(args)) From 1aad27b937bb576dff652d1969685cbde7f7e6fa Mon Sep 17 00:00:00 2001 From: vgallegoiz Date: Mon, 8 Apr 2024 23:32:57 +0200 Subject: [PATCH 03/10] Created toIP function and modified check_ping to work with ipaddress --- status.py | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/status.py b/status.py index 0ff9d96..151f10e 100644 --- a/status.py +++ b/status.py @@ -18,9 +18,7 @@ def parseArguments(): try: # Parsear los argumentos de la línea de comandos args = parser.parse_args() - if args.web and args.host: - return args.host, args.web - elif args.host: + if args.host: return args.host elif args.web: return args.web @@ -31,14 +29,32 @@ def parseArguments(): parser.print_help() exit() -def check_ping(host): - try: - response = ping(host, count=4, timeout=2) # verbose=True -> Para ver la respuesta del ping - return True if response.success() else False - except Exception as e: - print(f"Error making ping to {host}: {e}") - return False +def toIP(hosts): + ips = set() + for host in hosts: + try: + ip = ipaddress.IPv4Address(host) + ips.add(ip) + except ipaddress.AddressValueError: + print(f"La entrada '{ip}' no es una dirección IP válida.") + return ips + +def check_ping(hosts): + for host in hosts: + try: + print(f'Pingin host: {host}') + response = ping(str(host), count=4, timeout=2) # verbose=True -> Para ver la respuesta del ping + if not response.success(): + print(False) + # Ennviar un mensaje + else: + print(True) + except Exception as e: + print(f"Error making ping to {host}: {e}") if __name__ == '__main__': args = parseArguments() + hosts = read_document(args) + ips = toIP(hosts) + check_ping(ips) \ No newline at end of file From 166067972e7617623ce9c07cc4a9fd3839f20565 Mon Sep 17 00:00:00 2001 From: vgallegoiz Date: Mon, 8 Apr 2024 23:52:03 +0200 Subject: [PATCH 04/10] Changed main to define the structure of hosts and update --- status.py | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/status.py b/status.py index 151f10e..2633299 100644 --- a/status.py +++ b/status.py @@ -17,11 +17,7 @@ def parseArguments(): try: # Parsear los argumentos de la línea de comandos - args = parser.parse_args() - if args.host: - return args.host - elif args.web: - return args.web + return parser.parse_args() except argparse.ArgumentError as e: # Si ocurre un error al analizar los argumentos, mostrar un mensaje de error print("Error:", e) @@ -36,7 +32,7 @@ def toIP(hosts): ip = ipaddress.IPv4Address(host) ips.add(ip) except ipaddress.AddressValueError: - print(f"La entrada '{ip}' no es una dirección IP válida.") + print(f"La entrada '{host}' no es una dirección IP válida.") return ips def check_ping(hosts): @@ -55,6 +51,12 @@ def check_ping(hosts): if __name__ == '__main__': args = parseArguments() - hosts = read_document(args) - ips = toIP(hosts) - check_ping(ips) \ No newline at end of file + ips_and_hosts = set() + if args.host: + ips_and_hosts.update(toIP(read_document(args.host))) + print(ips_and_hosts) + if args.web: + print("Hay webs") + # Parsear correctamente + # ips_and_hosts.update() + check_ping(ips_and_hosts) \ No newline at end of file From 807517be9692c4dc65a43eb72ab53fe6b82dd8ce Mon Sep 17 00:00:00 2001 From: victor Date: Sun, 14 Apr 2024 13:24:09 +0200 Subject: [PATCH 05/10] Added send_discord_message() --- .env | 1 + status.py | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 .env diff --git a/.env b/.env new file mode 100644 index 0000000..97b1c54 --- /dev/null +++ b/.env @@ -0,0 +1 @@ +DISCORD_WEBHOOK_URL='https://discord.com/api/webhooks/1229025346385608824/kIt2dp2znu0jR85QbOPmoMAteHaB9BCJDTMfn0cHE9mwpxHkbUNc9By2Y7n6gpufoyco' diff --git a/status.py b/status.py index 2633299..0ee8b93 100644 --- a/status.py +++ b/status.py @@ -1,6 +1,11 @@ import argparse from pythonping import ping import ipaddress +import requests +import os +from dotenv import load_dotenv + +load_dotenv() def read_document(document_name): with open(document_name, 'r') as file: @@ -42,12 +47,24 @@ def check_ping(hosts): response = ping(str(host), count=4, timeout=2) # verbose=True -> Para ver la respuesta del ping if not response.success(): print(False) - # Ennviar un mensaje + send_discord_message(f"Ping fallido para el host: {host}") else: print(True) except Exception as e: print(f"Error making ping to {host}: {e}") +def send_discord_message(message): + webhook_url = os.getenv('DISCORD_WEBHOOK_URL') + data = { + "content": message + } + try: + response = requests.post(webhook_url, json=data) + response.raise_for_status() + except requests.exceptions.RequestException as e: + print(f"Error sending Discord message: {e}") + else: + print("Discord message sent successfully!") if __name__ == '__main__': args = parseArguments() From 7bccab94554bf767dcbafc3e36e515e03f0706d3 Mon Sep 17 00:00:00 2001 From: victor Date: Sun, 14 Apr 2024 13:47:50 +0200 Subject: [PATCH 06/10] dotenv no fuciona en RaspberryPi1 --- status.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/status.py b/status.py index 0ee8b93..797e93e 100644 --- a/status.py +++ b/status.py @@ -5,7 +5,7 @@ import requests import os from dotenv import load_dotenv -load_dotenv() +DISCORD_WEBHOOK_URL='https://discord.com/api/webhooks/1229025346385608824/kIt2dp2znu0jR85QbOPmoMAteHaB9BCJDTMfn0cHE9mwpxHkbUNc9By2Y7n6gpufoyco'load_dotenv() def read_document(document_name): with open(document_name, 'r') as file: @@ -54,12 +54,11 @@ def check_ping(hosts): print(f"Error making ping to {host}: {e}") def send_discord_message(message): - webhook_url = os.getenv('DISCORD_WEBHOOK_URL') data = { "content": message } try: - response = requests.post(webhook_url, json=data) + 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}") From 90a7cb8581e663fe6d886b08616c170ecb35b4b7 Mon Sep 17 00:00:00 2001 From: victor Date: Sun, 14 Apr 2024 13:48:26 +0200 Subject: [PATCH 07/10] dotenv no fuciona en RaspberryPi1 --- status.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/status.py b/status.py index 797e93e..211c6fa 100644 --- a/status.py +++ b/status.py @@ -5,7 +5,7 @@ import requests import os from dotenv import load_dotenv -DISCORD_WEBHOOK_URL='https://discord.com/api/webhooks/1229025346385608824/kIt2dp2znu0jR85QbOPmoMAteHaB9BCJDTMfn0cHE9mwpxHkbUNc9By2Y7n6gpufoyco'load_dotenv() +DISCORD_WEBHOOK_URL='https://discord.com/api/webhooks/1229025346385608824/kIt2dp2znu0jR85QbOPmoMAteHaB9BCJDTMfn0cHE9mwpxHkbUNc9By2Y7n6gpufoyco' def read_document(document_name): with open(document_name, 'r') as file: From 2b986eeabb8d4b8dff981cd92369b7d926c6efd9 Mon Sep 17 00:00:00 2001 From: victor Date: Sun, 14 Apr 2024 13:50:22 +0200 Subject: [PATCH 08/10] dotenv no fuciona en RaspberryPi1 --- status.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/status.py b/status.py index 211c6fa..cb3e9cd 100644 --- a/status.py +++ b/status.py @@ -2,8 +2,6 @@ import argparse from pythonping import ping import ipaddress import requests -import os -from dotenv import load_dotenv DISCORD_WEBHOOK_URL='https://discord.com/api/webhooks/1229025346385608824/kIt2dp2znu0jR85QbOPmoMAteHaB9BCJDTMfn0cHE9mwpxHkbUNc9By2Y7n6gpufoyco' From 6ab6224ff68fda59997f1ac32bb50fde4ae98fa6 Mon Sep 17 00:00:00 2001 From: victor Date: Sun, 14 Apr 2024 13:57:07 +0200 Subject: [PATCH 09/10] deleted prints --- status.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/status.py b/status.py index cb3e9cd..9750861 100644 --- a/status.py +++ b/status.py @@ -44,10 +44,7 @@ def check_ping(hosts): print(f'Pingin host: {host}') response = ping(str(host), count=4, timeout=2) # verbose=True -> Para ver la respuesta del ping if not response.success(): - print(False) send_discord_message(f"Ping fallido para el host: {host}") - else: - print(True) except Exception as e: print(f"Error making ping to {host}: {e}") @@ -68,7 +65,6 @@ if __name__ == '__main__': ips_and_hosts = set() if args.host: ips_and_hosts.update(toIP(read_document(args.host))) - print(ips_and_hosts) if args.web: print("Hay webs") # Parsear correctamente From aad6fb97a62408a4ddcfb910ed83c839db05ee10 Mon Sep 17 00:00:00 2001 From: victor Date: Sun, 14 Apr 2024 14:21:59 +0200 Subject: [PATCH 10/10] =?UTF-8?q?A=C3=B1adido=20sistema=20de=20logs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- status.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/status.py b/status.py index 9750861..f3b3f97 100644 --- a/status.py +++ b/status.py @@ -2,8 +2,10 @@ import argparse 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: @@ -41,12 +43,14 @@ def toIP(hosts): def check_ping(hosts): for host in hosts: try: - print(f'Pingin host: {host}') 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}") send_discord_message(f"Ping fallido para el host: {host}") + elif response.success(): + logging.info(f"Ping correct: {host}") except Exception as e: - print(f"Error making ping to {host}: {e}") + logging.info(f"Bad ping: {host}") def send_discord_message(message): data = { @@ -57,8 +61,9 @@ def send_discord_message(message): 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: - print("Discord message sent successfully!") + logging.info("Discord message sent successfully!") if __name__ == '__main__': args = parseArguments()