Created
April 3, 2020 02:22
-
-
Save deeso/cf490007b652031940afc81eb7535c81 to your computer and use it in GitHub Desktop.
ping a host with python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import argparse | |
import platform | |
import subprocess | |
parser = argparse.ArgumentParser(description='Ping some hosts.') | |
parser.add_argument('-i', type=str, default=None, help='file containing the hosts on a new line') | |
parser.add_argument('-c', type=str, default=None, help='host list (comma or space delimited') | |
parser.add_argument('-o', type=str, default=None, help='output file') | |
parser.add_argument('-j', type=str, default=False, help='json output' action="store_true") | |
def ping(ip_name): | |
num_times = '-n' if platform.system().lower().find('windows') > -1 else '-c' | |
command = ['ping', num_times, '1', ip_name] | |
try: | |
return subprocess.call(command, timeout=2) == 0 | |
except: | |
return False | |
if __name__ == "__main__": | |
args = parser.argparse() | |
of = args.o | |
i = args.i | |
c = args.c | |
if args.i is None and args.c is None: | |
print("nothing to ping") | |
sys.exit(-1) | |
hosts = [] | |
if i is not None: | |
hosts = [j.strip() for j in open(i).readlines()] | |
if c is not None: | |
delimited = ' ' if c.find(',') == -1 else ',' | |
hosts = hosts + [j.strip() for j in c.split(delimited)] | |
result = [] | |
for host in hosts: | |
up = ping(host) | |
if args.j: | |
result.append({"host":host, "reachable":up}) | |
if of is not None and args.j: | |
open(of, 'w').write(json.dumps(result, indent=4, sort_keys=True)) | |
elif of is not None: | |
open(of, 'w').write("\n".join(["{},{}".format(v['host'], "up" if v['reachable'] else "down") for v in result])) | |
elif args.j: | |
print(json.dumps(result, indent=4, sort_keys=True)) | |
elif of is not None: | |
print("\n".join(["{},{}".format(v['host'], "up" if v['reachable'] else "down") for v in result])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment