Skip to content

Instantly share code, notes, and snippets.

@cryzed
Created June 19, 2018 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cryzed/2918800e1b9b895a5a1e062bc45375a1 to your computer and use it in GitHub Desktop.
Save cryzed/2918800e1b9b895a5a1e062bc45375a1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import argparse
import shlex
import subprocess
import time
argument_parser = argparse.ArgumentParser()
argument_parser.add_argument('ip')
argument_parser.add_argument('--on-reachable', action='append', default=[])
argument_parser.add_argument('--not-reachable', action='append', default=[])
argument_parser.add_argument('--timeout', '-t', type=float)
argument_parser.add_argument('--interval', '-i', type=float, default=1)
def is_reachable(address, timeout=None):
command = ['ping', '-c', '1', '-q', '-n']
if timeout is not None:
command.extend(['-W', str(timeout)])
command.append(address)
process = subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return not process.returncode
def execute(command_string):
command = shlex.split(command_string)
return subprocess.run(command)
def main(arguments):
was_reachable = False
while True:
reachable = is_reachable(arguments.ip, arguments.timeout)
if was_reachable is not reachable:
was_reachable = reachable
commands = arguments.on_reachable if reachable else arguments.not_reachable
for command in commands:
execute(command)
time.sleep(arguments.interval)
if __name__ == '__main__':
arguments = argument_parser.parse_args()
argument_parser.exit(main(arguments))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment