Using for loop in python to test ping response from multiple hosts

Today let us have a look at an interesting python script to test ping connectivity on a list of hosts.

To understand this lets create below script and a hosts file, then execute it.

1. Create a Python Script for Ping

$ cat hostping.py 
import socket  # For connecting two nodes on a network to communicate with each other
import sys     # To get access to some variables used/maintained by interpreter and function that interact with interpreter
import os      # Allows an interface with the OS that Python is running on.


file = open("./host.txt","r")
for server_name in file:
        server_state = os.system('ping -c 2 ' + server_name )
        if server_state == 0:
                print(server_name +"===== Server is UP=====")
        else:
                print("=====Server is DOWN====")

$ 

2. Create the file host.txt containing all hosts on which we need to test ping.

$ cat host.txt 
r001-ngelinux.com
r002-ngelinux.com
r003-ngelinux.com
r004-ngelinux.com
r005-ngelinux.com
r006-ngelinux.com
r007-ngelinux.com
r008-ngelinux.com
r009-ngelinux.com
r010-ngelinux.com
r011-ngelinux.com
r012-ngelinux.com
r013-ngelinux.com
r014-ngelinux.com
r015-ngelinux.com
r016-ngelinux.com
r017-ngelinux.com
r018-ngelinux.com
r019-ngelinux.com
r020-ngelinux.com
$ 

3. Run the script and check output.

$ python ./hostping.py 
PING r001-ngelinux.com (10.24.80.9): 56 data bytes
64 bytes from 10.24.80.9: icmp_seq=0 ttl=50 time=297.965 ms
64 bytes from 10.24.80.9: icmp_seq=1 ttl=50 time=298.016 ms

--- r001-ngelinux.com ping statistics ---
2 packets transmitted, 2 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 297.965/297.990/298.016/0.026 ms
r001-ngelinux.com
===== Server is UP=====
PING r002-ngelinux.com (10.24.88.9): 56 data bytes
64 bytes from 10.24.88.9: icmp_seq=0 ttl=49 time=303.543 ms
64 bytes from 10.24.88.9: icmp_seq=1 ttl=49 time=303.368 ms

--- r002-ngelinux.com ping statistics ---
2 packets transmitted, 2 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 303.368/303.456/303.543/0.087 ms
r002-ngelinux.com
===== Server is UP=====
PING r003-ngelinux.com (10.24.96.9): 56 data bytes
64 bytes from 10.24.96.9: icmp_seq=0 ttl=49 time=342.405 ms
64 bytes from 10.24.96.9: icmp_seq=1 ttl=49 time=342.275 ms

--- r003-ngelinux.com ping statistics ---
2 packets transmitted, 2 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 342.275/342.340/342.405/0.065 ms
r003-ngelinux.com
===== Server is UP=====
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments