Python Ping Script

Python Ping Script

This is a handy little script I wrote for a personal project a while back. There’s already plenty of these on the Internet but sometimes its nice to see a finished article – and have the opportunity to copy and amend the code to suit your own needs.

Overview

This is a Python script designed to read in IP addresses from a CSV file, ping them to check if they are online, and then display results on the console window.

The CSV file will contain the IP addresses to scan, but will also contain some vanity information for each entry – so the format of the columns CSV file should be as below, so column 1 should have a displayname, column 2 should have description and column 3 should contain the IP address.

Displayname Description IP address

Note: This script is intentionally kept lean and easy to use so it can be used as a basis for complex projects if needed. This means that you should consider adding in IP validation, error checking, exception checking and some multi-threading.

Note: Tested on Python 3.5.1

import subprocess
import csv

#   --------------------------------------------
# 	Script settings
#   --------------------------------------------

# This is the location of the CSV file
csvLocation = "C:\\Users\\username\\desktop\\ipaddresses.csv" 
# This will be the number of pings per IP address 
numberOfPings = "2"

#   --------------------------------------------
#   ping (String, String)
#   --------------------------------------------
def ping(host, numberOfPings):
    ping = subprocess.Popen(["ping", "-n", numberOfPings, host],stdout = subprocess.PIPE) 
    out, error = ping.communicate()
    out = out.strip() 
    status = False
    if "TTL" in str(out):
        status = True
    return status

#   --------------------------------------------
#   startScan (string)
#   -------------------------------------------- 
def startScan(csv_file):
  routersTotal = 0
  
  # Loop through rows in CSV file
  for row in csv.reader(csv_file, delimiter=','):
    routersTotal += 1
    # Check if router is online or offline
    status = "Offline" 
    if ping(row[2], numberOfPings):   
      status = "Online"
      routersOnline += 1 
    # Print result to console    
    print (status + " - " + row[0] + " (" + row[2] +")")
             
  # Print overall result of scans    
  print (str(routersOnline) + "/" + str(routersTotal) + " online") 
    
#   --------------------------------------------
#   SCRIPT START POINT 
#   -------------------------------------------- 

startScan(csvLocation)


Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>