我相信这不是最好的解决方案,但可以满足您的要求。该脚本ping
在192.168.0.0/24
网络上运行,如果ARP缓存中没有IP地址,则返回无效IP的列表。
与先前解决方案相比的优势:
- 使用两种方法:ping和ARP检查
- 无需以
root
用户身份运行
- 在我的Core i3-2100上运行约1.5分钟
要扫描您的网络,请使用<first IP> <last IP>
参数运行它。
#!/usr/bin/env python
from threading import Thread
import subprocess
from Queue import Queue
verbose = False
num_threads = 8
queue = Queue()
inactive_ips = [0 for i in range(256)]
lines = open("/proc/net/arp", "r").readlines()
arp_cache = [l.split()[0] for l in lines[1:] if l.split()[2] == "0x2"]
def ip_str_to_int(ip):
ip = ip.rstrip().split('.')
ipn = 0
while ip:
ipn = (ipn << 8) + int(ip.pop(0))
return ipn
def ip_int_to_str(ip):
ips = ''
for i in range(4):
ip, n = divmod(ip, 256)
ips = str(n) + '.' + ips
return ips[:-1] ## take out extra point
#wraps system ping command
def pinger(i, q):
while True:
ip_num = q.get()
ip = ip_int_to_str(ip_num)
if ip not in arp_cache:
ret = subprocess.call("ping -c 1 %s" % ip,
shell=True,
stdout=open('/dev/null', 'w'),
stderr=subprocess.STDOUT)
if ret != 0:
inactive_ips[ip_num % 256] = ip
q.task_done()
if __name__ == '__main__':
from optparse import OptionParser
usage = "usage: %prog [options] [first IP] [last IP]"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="make lots of noise")
parser.add_option("-q", action="store_false", dest="verbose", help="print only IP adresses")
(options, args) = parser.parse_args()
verbose = options.verbose
first = ip_str_to_int(args[0] if len(args) > 0 else "192.168.0.1")
last = ip_str_to_int(args[1] if len(args) > 1 else "192.168.0.254")
if verbose:
print "Scanning inactive network addresses from %s to %s" % (
ip_int_to_str(first),
ip_int_to_str(last))
for i in range(num_threads):
worker = Thread(target=pinger, args=(i, queue))
worker.setDaemon(True)
worker.start()
for ip in range(first, last + 1):
queue.put(ip)
queue.join()
for ip in inactive_ips:
if ip:
print ip
下票后更新
我写它是因为nmap -PR 192.168.0.*
对我不起作用:
Starting Nmap 5.21 ( http://nmap.org ) at 2011-10-06 15:34 EEST
Nmap done: 256 IP addresses (0 hosts up) scanned in 0.03 seconds
更新2
修复了ARP缓存的所有问题。