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
inenviarPing
)? Since it’s ping one at a time... The goal was 255 threads, each one ping a different address all at the same time– Miguel
What is the IP range?
– Miguel
@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.
– stderr