73 lines
2.1 KiB
Python
73 lines
2.1 KiB
Python
from .ping import Ping
|
|
import time
|
|
import typing as t
|
|
import sqlite3
|
|
import argparse
|
|
import logging
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def record(target: str, interval: int, outage_interval: int):
|
|
"""Record errors while pinging `target` each `interval` seconds"""
|
|
|
|
ping = Ping(target)
|
|
db = sqlite3.connect("netmon.sqlite3")
|
|
|
|
outage: t.Optional[int] = None
|
|
|
|
try:
|
|
while True:
|
|
res = ping.ping()
|
|
if outage is None and not res: # beginning of outage
|
|
outage = int(time.time())
|
|
logger.info("Could not reach target.")
|
|
|
|
elif outage is not None and res: # end of outage
|
|
delta = int(time.time() - outage)
|
|
logger.info(
|
|
"Could reach target again (out for %d min %d s)",
|
|
delta // 60,
|
|
delta % 60,
|
|
)
|
|
with db:
|
|
db.execute(
|
|
"INSERT INTO errors (from_time, to_time, host) VALUES (?, ?, ?);",
|
|
(int(outage), int(time.time()), target),
|
|
)
|
|
outage = None
|
|
time.sleep(interval if outage is None else outage_interval)
|
|
except KeyboardInterrupt as exn:
|
|
if outage is not None:
|
|
with db:
|
|
db.execute(
|
|
"INSERT INTO errors (from_time, to_time, host) VALUES (?, ?, ?);",
|
|
(int(outage), int(time.time()), target),
|
|
)
|
|
raise exn
|
|
|
|
|
|
def entry():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("host", help="Remote host to ping (IP address preferred)")
|
|
parser.add_argument(
|
|
"-i", "--interval", default=30, type=int, help="Time between two pings"
|
|
)
|
|
parser.add_argument(
|
|
"-I",
|
|
"--outage-interval",
|
|
default=2,
|
|
type=int,
|
|
help="Time between two pings while the network is down",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
record(args.host, args.interval, args.outage_interval)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
entry()
|