be66a7caed9ebc11e6f30cf9a216047e29a5e4c3
David Blume first commit.

David Blume authored 5 years ago

1) #!/usr/bin/python3
2) #
3) # Since this is meant to be run as a daemon, do not use #!/usr/bin/env python3,
4) # because the process name would then be python3, not based on __FILE__.
5) #
6) # [filename] -d 3 192.168.1.1 192.168.1.12 &
7) # disown [jobid]
8) import os
9) import sys
10) import subprocess
11) import time
12) from argparse import ArgumentParser
13) import threading
14) import queue
David Blume Add notifications for SIGTE...

David Blume authored 5 years ago

15) import signal
David Blume first commit.

David Blume authored 5 years ago

16) 
David Blume Serialize the reading and w...

David Blume authored 5 years ago

17) pinger_lock = threading.Lock()
18) 
David Blume first commit.

David Blume authored 5 years ago

19) 
David Blume Rename a parameter instead...

David Blume authored 5 years ago

20) def log_exit(sig, frame):
21)     _print_queue.put([f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())} '
22)                       f'PID={os.getpid()} signal={signal.Signals(sig).name} Exiting.'])
David Blume Add notifications for SIGTE...

David Blume authored 5 years ago

23)     _print_queue.join()
24)     sys.exit(0)
25) 
26) 
David Blume first commit.

David Blume authored 5 years ago

27) def pinger(host):
28)     """Executes one ping, prints if there was a change, exits thread."""
29)     now = time.localtime()
30)     success = ping(host)
David Blume Serialize the reading and w...

David Blume authored 5 years ago

31)     with pinger_lock:
32)         # Access to _results needs to be serialized
33)         need_update = success != _results[host]
34)         if need_update:
35)             _results[host] = success
36)     if need_update:
David Blume first commit.

David Blume authored 5 years ago

37)         status = "UP" if success else "DOWN"
38)         _print_queue.put([f'{time.strftime("%Y-%m-%d %H:%M:%S", now)} {host} {status}'])
39) 
40) 
41) def ping(host):
42)     """Returns True if host (str) responds to a ping request."""
43)     return subprocess.call([*_ping_cmd, host], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0
44) 
45) 
46) def print_manager():
47)     """ The only thread allowed to write output. """
48)     while True:
49)         job = _print_queue.get()
50)         for line in job:
51)             log(line)
52)         _print_queue.task_done()
53) 
54) 
55) def log(*args, **kwargs):
56)     """Opens the logfile, writes the log, and closes the logfile."""
57)     # I don't leave the log file open for writing because another process needs access too.
58)     with open(_logname, 'a') as fp:
59)         return print(*args, **kwargs, file=fp)
60) 
61) 
62) if __name__ == '__main__':
63)     parser = ArgumentParser(description="Repeatedly ping sites. Ex: %(prog)s -d 3 192.168.1.1 192.168.1.12")
David Blume Add notifications for SIGTE...

David Blume authored 5 years ago

64)     parser.add_argument('-d', '--delay', type=float, default=3.0, help='Delay between pings')
David Blume first commit.

David Blume authored 5 years ago

65)     parser.add_argument('addresses', nargs='+', help='Addresses to ping')
66)     parser_args = parser.parse_args()
67) 
68)     _results = dict()
69)     for addr in parser_args.addresses:
70)         _results[addr] = None
71)     delay = parser_args.delay
72)     _logname = os.path.join(os.path.expanduser('~'), 'log', os.path.basename(sys.argv[0]).replace('py', 'txt'))
73) 
74)     # Choose the ping parameters appropriate for the platform
75)     if sys.platform == 'cygwin' or sys.platform == 'win32':
76)         _ping_cmd = ('ping', '-n', '1', '-w', '2000')
77)     else:
78)         _ping_cmd = ('ping', '-c', '1', '-W', '2', '-q')
79) 
80)     _print_queue = queue.Queue()
81)     t = threading.Thread(target=print_manager, daemon=True)
82)     t.start()
83)     del t
84) 
David Blume Add notifications for SIGTE...

David Blume authored 5 years ago

85)     signal.signal(signal.SIGINT, log_exit)
86)     signal.signal(signal.SIGTERM, log_exit)
87) 
David Blume first commit.

David Blume authored 5 years ago

88)     _print_queue.put([f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}'
David Blume Add notifications for SIGTE...

David Blume authored 5 years ago

89)         f' PID={os.getpid()} repeat={delay}s addresses={",".join(parser_args.addresses)} Starting'])