httpoll/httpoll.py

75 lines
1.9 KiB
Python
Raw Normal View History

2023-08-18 14:43:41 +02:00
#!/usr/bin/python3
import argparse
import requests
2023-11-15 19:05:04 +01:00
import urllib3
import time
from datetime import datetime
import os
import sys
from rich import print
2023-08-18 14:43:41 +02:00
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
2023-11-15 19:05:04 +01:00
args = dict()
proxy = {
"http": os.environ.get('http_proxy'),
"https": os.environ.get('https_proxy')
}
2023-08-18 14:43:41 +02:00
def poll(url):
2023-08-18 14:43:41 +02:00
"""Try to HTTP GET the URL."""
status, result = "", ""
time_start = time.time()
2023-08-18 14:43:41 +02:00
try:
r = requests.get(url=url, timeout=50.0,
2023-11-15 19:05:04 +01:00
verify=False, proxies=proxy)
status = "[bold green] up[/bold green]"
2023-08-18 14:43:41 +02:00
result = str(r)
except requests.exceptions.RequestException as e:
status = "[bold red] down[/bold red]"
2023-08-18 14:43:41 +02:00
result = str(e)
return {
"duration": (time.time() - time_start),
"status": status,
"result": result
}
2023-08-18 14:43:41 +02:00
def run(global_time_start):
2023-08-18 14:43:41 +02:00
"""Runs endlessly but at most once per second."""
while True:
time_start = time.time()
results = []
for target in args.URL:
results.append(poll(target))
global_time = datetime.now().replace(microsecond=0) - global_time_start
print(f"time: {global_time} | ", end="")
for index, result in enumerate(results):
print(f"pa{index}: {result['status']}\t |", end="")
print()
time_elapsed = time.time() - time_start
time_to_sleep = max(1.0 - time_elapsed, 0)
time.sleep(time_to_sleep)
2023-08-18 14:43:41 +02:00
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser()
parser.add_argument('URL', nargs='*')
2023-11-15 19:05:04 +01:00
parser.add_argument('--no-proxy', action="store_true")
2023-08-18 14:43:41 +02:00
args = parser.parse_args()
2023-11-15 19:05:04 +01:00
if args.no_proxy:
proxy = {'no': 'pass'}
2023-08-18 14:43:41 +02:00
global_time_start = datetime.now().replace(microsecond=0)
run(global_time_start)
2023-08-18 14:43:41 +02:00
except KeyboardInterrupt:
sys.exit()