Si l'on souhaites savoir si plusieurs PC sont accessiblent nous utilisons la commande PING. Mais il y a un soucie. Si l'on ping un PC qui à un timeout, nous mettons du temps à le savoir. Et lorsque l'on scan à travers un vaste réseaux de PC qui ne répondent pas, cela commence à prendre beaucoup de temps!
Voici un programme qui ping 10 host en utilisant les threads.
Ainsi le meme scan prends désormais 3,28secondes a la place de 28!
[code:1:98a594d74c]import os
import re
import time
import sys
from threading import Thread
class testit(Thread):
def __init__ (self,ip):
Thread.__init__(self)
self.ip = ip
self.status = -1
def run(self):
pingaling = os.popen("ping -q -c2 "+self.ip,"r")
while 1:
line = pingaling.readline()
if not line: break
igot = re.findall(testit.lifeline,line)
if igot:
self.status = int(igot[0])
testit.lifeline = re.compile(r"(\d) received")
report = ("No response","Partial Response","Alive")
print time.ctime()
pinglist = []
for host in range(0,10):
ip = "192.168.2."+str(host)
current = testit(ip)
pinglist.append(current)
current.start()
for pingle in pinglist:
pingle.join()
print "Status from ",pingle.ip,"is",report[pingle.status]
print time.ctime()[/code:1:98a594d74c]
A l'exécution:
[code:1:98a594d74c][mik@mik-desktop:/tmp$ mik@mik-desktop:/tmp$ sudo python ping.py
mik@mik-desktop:/tmp$ sudo python ping.py
Sun Feb 17 22:58:16 2008
Do you want to ping broadcast? Then -b
Status from 192.168.2.0 is Alive
Status from 192.168.2.1 is Alive
Status from 192.168.2.2 is No response
Status from 192.168.2.3 is No response
Status from 192.168.2.4 is No response
Status from 192.168.2.5 is No response
Status from 192.168.2.6 is No response
Status from 192.168.2.7 is No response
Status from 192.168.2.8 is No response
Status from 192.168.2.9 is No response
Sun Feb 17 22:58:19 2008
mik@mik-desktop:/tmp$
[/code:1:98a594d74c]
[b:98a594d74c]
Comment cela fonctionne?[/b:98a594d74c]
Nous lançons des ping en parallèle sur chacuns des host.
Pour chacun, un objet héritant de la classe thread est créé.
Source: http://www.wellho.net/solutions/python-python-threads-a-first-example.html