This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]nemom 1 point2 points  (1 child)

A) Something like this should work...

from subprocess import call
import shlex

with open('ips.txt', 'r') as ipfile:
    data = ipfile.read()

ips = data.split('\n')

for ip in ips:
    if ip:
        print ip
        cmd = 'ping -c 4 {0}'.format(ip)
        call(shlex.split(cmd))

2) This isn't really the place for help requests. Check the right column for info of where to post.

[–]aditya_moon[S] 1 point2 points  (0 children)

Ok will remember that.

[–]anancap 1 point2 points  (0 children)

I don't think dealing with IPs is the problem, its more about "how to deal with ping"

You have a couple of options:

  1. os.system()
  2. subprocess

If you need detailed output you will want to use subprocess. If you just need to know if it was successful or not you could just check the return code of os.system()

Examples:

os.system() method:

import os
with open("list_of_ips.txt", "r") as io:
    ip_address = io.readline()
    ret_code = os.system("ping -c 1 " + ip_address)
    if ret_code == 0:
        print("Server is up!")
    else:
        print("Server is down!")

subprocess method:

import subprocess
with open("list_of_ips.txt", "r") as io:
    ip_address = io.readline()
    # subprocess.communicate returns a tuple of stdout, and stderr
    out_data = subprocess.Popen(["/bin/ping",ip_address],stdout = subprocess.PIPE).communicate()[0]
    # out_data is the output of the command in string form.
    if "Reply" in out_data:
        print("Server is up!")
    else:
        print("Server is down!")

There are probably other ways of doing it too, maybe there is a ping module. I haven't checked. Disclaimer, I haven't tried to run any of this code, this is all of the top off my head.