Ping - save positive results to a list

2

I have this code, it works fine, but the problem is that I would like to save the successes (ping with return) in a list , but I do not know how to do this trace successes / failures. >

import subprocess
import threading

def pinger_menager():

   count = 1
   while count <= 255:
      address = "192.168.1."+str(count)
      for i in xrange(1, 2):
         worker = threading.Thread(target=massive_pinger, args=(address,))
         worker.start()

      count = count + 1

 def massive_pinger(address):
    try:
       res = subprocess.call(['ping', '-c', '1', address])
    except:
       pass 

 def main():
    pinger_menager()

main()
    
asked by anonymous 25.03.2015 / 19:43

1 answer

2

One way to know this is to check the return of the subprocess.call function, is returned 0 if it succeeds, or 1 if it fails.

To save the results in a list you will have to create an array :

lista = []

In function massive_pinger check the value of res variable:

def massive_pinger(address):
    try:
        res = subprocess.call(['ping', '-c', '1', address], stdout=subprocess.PIPE, 
        stderr=subprocess.PIPE)
        if res == 0: # Obteve sucesso
            lista.append(address)
    except:
        pass 

To print the addresses of the list just do:

def main():
   pinger_menager()
   for endereco in lista:
      print(endereco)

As you are using threads , you can implement the code a bit with Queue .

Consider the code below, based on yours, but with a slightly different approach, using a class :

from subprocess import check_output, CalledProcessError
from threading import Thread
from Queue import Queue

class PingNetwork:
    def __init__(self):
        self.lista = []
        self.queue = Queue()

    def pingManager(self, endereco):
        self.endereco = endereco
        alcance = 256
        for contagem in range(1, alcance):
            alvo = "{0}.{1}".format(self.endereco, contagem)
            self.queue.put(alvo) # Coloca o endereco atual na fila
            worker = Thread(target=self.enviarPing)
            worker.setDaemon(True)
            worker.start()
        self.queue.join() # O trabalho foi terminado

    def enviarPing(self):
        endereco = self.queue.get() # Retorna o endereco atual e remove o mesmo da fila
        try:
            check_output(['ping', '-c', '1', endereco])
            self.lista.append(endereco)
        except CalledProcessError: # Se a tentativa de ping falhar, a exceção é lançada
            pass # Operação nula, nada acontece
        self.queue.task_done() # A tarefa atual foi terminada

    def obterLista(self):
        return self.lista

The trick is to use the check_output method, if attempting to ping fails, an exception CalledProcessError is thrown, otherwise it indicates that the ping attempt succeeded.

To use in the main function:

def main():
    ping = PingNetwork()
    ping.pingManager('192.168.1')
    enderecos = ping.obterLista()

    for endereco in enderecos:
        print ("O endereco {0} respondeu com sucesso".format(endereco))

if __name__ == "__main__":
    main()
    
26.03.2015 / 00:07