Python Ping Script: Ping a list of hosts/servers from a file in python ?

Lets start with python programming and see how to ping a list of servers from a hosts file.

First lets start with program.

I. Program

import os

hostsfile=open("hosts", "r")

lines=hostsfile.readlines()

for line in lines:
    response=os.system("ping -c 1 " + line)
    if (response == 0):
        status = line.rstrip() + " is Reachable"
    else:
        status = line + " is Not reachable"
    print(status)

a. Here we have opened a file named “hosts” read only and taken its content in a variable named “lines”
b. Now we read this content line by line and pinged each host.
c. In the end, printed the ping response on screen.

 

II. Hosts file with name “hosts”

localhost
google.com
ngelinux.com

 

III. Output

/Users/saket/PycharmProjects/programs/venv/bin/python /Users/saket/PycharmProjects/programs/ping_program.py
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.054 ms

--- localhost ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.054/0.054/0.054/0.000 ms
localhost is Reachable
PING google.com (216.58.196.78): 56 data bytes
64 bytes from 216.58.196.78: icmp_seq=0 ttl=46 time=525.641 ms

--- google.com ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 525.641/525.641/525.641/0.000 ms
google.com is Reachable
PING ngelinux.com (104.152.168.40): 56 data bytes

--- ngelinux.com ping statistics ---
1 packets transmitted, 0 packets received, 100.0% packet loss
ngelinux.com is Not reachable

Process finished with exit code 0

 

IV. Nice program with subprocess library supressing ping output

import subprocess

hostsfile=open("hosts", "r")

lines=hostsfile.readlines()

for line in lines:
    response=subprocess.Popen(["ping", "-c", "1", line.strip()],
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT)
    stdout, stderr = response.communicate()
    #print(stdout)
    #print(stderr)

    if (response.returncode == 0):
        status = line.rstrip() + " is Reachable"
    else:
        status = line.rstrip() + " is Not reachable"
    print(status)

In above example, we have used subprocess library instead of os, which is recommended.
Here we have not printed the ping output, and simply printed the result.

Hosts File

localhost
google.com
ngelinux.com
ngelinux2.com

 

V. Output

/Users/saket/PycharmProjects/programs/venv/bin/python /Users/saket/PycharmProjects/programs/ping_program.py
localhost is Reachable
google.com is Reachable
ngelinux.com is Reachable
ngelinux2.com is Not reachable

Leave a Reply

avatar
  Subscribe  
Notify of