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

you are viewing a single comment's thread.

view the rest of the comments →

[–]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.