0

I wrote some code to ping the servers but I don't want the output on the screen. But even after sending the output to /dev/null I am getting all the ping details on the screen.

#!/usr/bin/python
import os
import sys
with open(sys.argv[1]) as servers:
    for host in servers:
        response = os.system("ping -q -c 1 "+host+">/dev/null 2>&1")
        if response==0:
            print(host)
        else:
            print(host+"is dead")
Tom Tanner
  • 9,244
  • 3
  • 33
  • 61
Shankar Kumar
  • 87
  • 1
  • 8

2 Answers2

0

Use this:

import subprocess

def myping():
    with open(sys.argv[1]) as servers:
        for host in servers:
            p = subprocess.Popen(["ping", "-q", "-c", "1", host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            response = p.wait()
            if response==0:
                print(host+"is dead")
            else:
                print(host+"is up")

myping()

Demo

>>> import subprocess 
>>> host = "google.com"
>>> p = subprocess.Popen(["ping", "-q", "-c", "1", host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> response = p.wait()
>>> print response
1
sinhayash
  • 2,693
  • 4
  • 19
  • 51
0
import subprocess
p = subprocess.Popen(["ping", "-q", "-c", "1", host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return_code = p.wait()

Avoid using os.system. It is deprecated, and outdated.

FunkySayu
  • 7,641
  • 10
  • 38
  • 61