要查看目前網段存活的主機,對好的方式就是用ping,用bash跑for 簡單!
但是1~255的ip,每一個ping 最快1秒,至少也要 255秒,將近5分鐘的時間!泡麵也都快爛掉了
所以找了一些方式來縮短時間,這裡是用python2.7來執行,需要import 的有threading 、 subprocess ,使用多執行緒來進行ping的任務。
繼承threading.Thread,來複寫__init__ 、 run 兩個方法
用subprocess.Popen 來執行ping 指令,使用PIPE來取得相關的字段
#!/usr/bin/env python
import threading
import subprocess
""" 繼承theading.Thread """
class myThread(threading.Thread):
def __init__(self, counter):
threading.Thread.__init__(self)
self.counter = counter
def run(self):
ping(self.name, self.counter)
def ping(threadName, IPnumber):
""" -c 表示只執行次數 """
cmd = ['ping','-c','1','192.168.1.'+ str(IPnumber)]
""" 執行 ping 指令,並且轉由grep取得ttl字串"""
p_cmd = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
formatCmd = subprocess.Popen(['grep','ttl'], stdin=p_cmd.stdout, stdout=subprocess.PIPE)
stdout, stderr = formatCmd.communicate()
if formatCmd.returncode > 0:
pass
#print stderr
else:
print stdout,
number = 255
while number:
Thread1 = myThread( number )
Thread1.start()
number -= 1
print "Exiting Main Thread"
這是一個簡易型可以快速ping主機的方式,用效能換時間,不然身體都快長蜘蛛網了...!