Ping - store positive results in a list

Asked

Viewed 519 times

2

I have this code, it’s working fine, but the problem is that I would like to save the hits (ping with feedback) in a list, but I don’t know how to do this screening 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()

1 answer

2


One way to know this is to check the function return subprocess.call, is returned 0 if successful, or 1 should I fail.

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

lista = []

In function massive_pinger check the variable value res:

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 list addresses just do:

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

How are you using threads, it is possible to implement some code with the class Queue.

Consider the code below, based on your own, 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 method check_output, if the attempt to ping fail, an exception CalledProcessError is launched, otherwise indicates that the attempt to ping 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()
  • The timeout I’ve noticed. But with the mechanics so what is the purpose of threads (make a print endereço in enviarPing)? Since it’s ping one at a time... The goal was 255 threads, each one ping a different address all at the same time

  • What is the IP range?

  • @Miguel I fixed the code. It looked more like yours, I left the timeout of side to do this what you want. I later edit and detail the code better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.