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()