Skip to content

Instantly share code, notes, and snippets.

@twstagg
Last active November 2, 2019 17:08
Show Gist options
  • Save twstagg/8c53d7b314fb4e3a73762f45b8ae72d4 to your computer and use it in GitHub Desktop.
Save twstagg/8c53d7b314fb4e3a73762f45b8ae72d4 to your computer and use it in GitHub Desktop.
A simple python3 script to iterate through a list of hostnames or IP addresses, ping them, and filter offline devices
#!/usr/bin/env python3
import sys
import platform
import subprocess
import argparse
import magic
def pingAllTargets(path, plat):
with open(path, "r") as targets:
for line in targets:
line = line.rstrip()
if "Windows" in plat:
ping = ['ping', '-n', '1', line]
else:
ping = ['ping', '-c', '1', line]
status = subprocess.call(
ping, stdout=subprocess.PIPE)
if status == 0:
print("%s: OK" % line)
else:
print("%s: OFFLINE" % line)
def main():
plat = platform.system()
parser = argparse.ArgumentParser(description="ping_range.py")
parser.add_argument('file', metavar='file',
help="list of targets to ping")
args = parser.parse_args()
path = args.file.lower()
fileName = args.file
try:
fileType = str(magic.from_file(fileName))
except OSError:
print("OSError: file '%s' does not exist!" % fileName)
sys.exit()
if "ASCII text" in fileType:
pingAllTargets(path, plat)
else:
print("Error: please use a plain text file separating individual",
"hostname/ip with new line")
sys.exit()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment