Home > Others > A simple python script for pinging multiple IPs from a file.

A simple python script for pinging multiple IPs from a file.

Pinging is simple but powerful and it is used often to test and verify connectivity. This short Python script will save IT pros a lot of time when they want to ping multiple IPs. This script can work on any Windows or Linux platform.

https://github.com/jakgul/ping

import os
import subprocess
import platform
import ipaddress

class Smartping():

    def __init__(self,ips=[],ping_count=2, subnet=""):
        self.ips=ips
        self.ping_count = ping_count
        self.subnet = subnet
        self.platform = platform.system().lower()
        self.ping_result = ""
        self.flattened_ips=[]  #IPs will be added here

    def flatten_ips(self):
        for ip in self.ips:
            if "/" in ip:  #convert network address to IPs
                self.load_ips_from_subnet(ip)
            else:
                self.flattened_ips.append(ip)

    def ping(self):
        self.flatten_ips()
        if self.platform == "windows":
            self.windows_ping()
        else:
            self.linux_ping()

    def linux_ping(self):
        for ip in self.flattened_ips:
            command = "ping -c {} {}".format(str(self.ping_count), ip)  #EX: ping -c 1 10.10.10.1  (send 1 ping)
            response = os.system(command)
            if response == 0:
                self.ping_result += ip + " is up!\n"
            else:
                self.ping_result += ip + " is down!\n"
        print(self.ping_result)

    def windows_ping(self):
        for ip in self.flattened_ips:
            command = "ping -n {} {}".format(str(self.ping_count), ip)   #EX: ping -n 1 10.10.10.1  (send 1 ping)
            response = subprocess.run(command, capture_output=True)
            output = response.stdout.decode()
            print(output)
            if "Destination host unreachable" in output:
                self.ping_result += ip + " is down! Destination host unreachable. \n"
            elif "Request timed out" in output:
                self.ping_result += ip + " is down! Request timed out.\n"
            else:
                self.ping_result += ip + " is up!\n"
        print(self.ping_result)

    def load_ips(self,filename):
        with open(filename) as file:  #load IPs from a spesific file
            ip_text_file = file.read()
            self.ips = ip_text_file.split("\n")


    def load_ips_from_subnet(self,subnet):
        for addr in ipaddress.ip_network(subnet):  #find all the IPs in network, add it to list
            self.flattened_ips.append(str(addr))

    def save_output(self,filename="pingresult.txt"):  #write the ping result to a file
        file = open(filename, "w")
        file.write(self.ping_result)
        file.close()


############################################
#Run the script by editing below
############################################

#Step 1, call the class object and create a smartping object
a = Smartping()

#Step 2, load IPs.
a.load_ips("devices.txt")    #load IPs from file
#a.ips = ["10.70.69.0/30","10.70.70.2","10.70.70.3"] #load IPs as a list

# Step 3 Specify the ping count(default is 2)
a.ping_count = 1
#Step 4, call the ping function
a.ping()

#Step 5, save the ping results to a file. Default file name is pingresult.txt or specify the name
a.save_output("writehere.txt")


Run the scripts with below simple steps.

  1. Install python 3.
  2. Create a devices.txt file in the same directory where you will save the script.
  3. Put each IP or hostname in devices.txt as shown below. (one IP, network address or name for each line)

4. Edit the last part of the script. The script allows you to customize how you want to load IPs. You can comment or uncomment some lines depends on your needs.

5. On Linux, you can run the script in the command line. On windows, script can be run in windows python interpreter.

python3 ping.py 

10.10.10.1 is down!
10.10.2.0 is down!
10.10.10.0 is down!
10.10.10.1 is down!
10.10.10.2 is down!
10.10.10.3 is down!
2.2.2.2 is down!
google.com is up!

You can customize the output text and ping counts for each IPs. I suggest sending minimum 2 pings since first ping might fail in the process of ARP.

Hope this helps. Please let me know in the comments what you do to save time when you need to ping multiple IPs.

3 thoughts on “A simple python script for pinging multiple IPs from a file.

  1. Thanks for the script, Jacob. I did exactly what you had stated. Created devices.txt file with IP on each line and ran the command. only way it worked when I removed “-c 2” which would result in 4 ping reply. any tips? i am using windows 10 with python3.

    Below is the error:

    Bad value for option -c 2.
    Bad value for option -c 2.

    ping to 8.8.8.8 failed!
    ping to 8.8.4.4 failed!
    *********************************************************************

    import subprocess
    ping_result = “\n\n”
    with open(‘devices.txt’) as f:
    for line in f:
    address = line.strip(“\n”)

    res = subprocess.call([“ping”, “-c 2”, address])
    if res == 0:
    ping_result = ping_result + “ping to ” + address + ” OK” + ” \n”
    elif res == 2:
    ping_result = ping_result + “no response from ” + address + ” \n”
    else:
    ping_result = ping_result + “ping to ” + address + ” failed!” + ” \n”

    print (ping_result)

    1. Hello,

      “-c” is used for specifying ping count in Linux. However, this is -n in windows. I updated the script with a newer version. Please try and let me know if it works.

Leave a Reply

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