1

我正在尝试以最快的方式打印连接到我的网络的所有实时 IP。我尝试在 for 循环中执行 ping 操作,但速度很慢:

def PingTry(host):
    ping = subprocess.Popen(["ping", host], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    out, error = ping.communicate()
    print out #This will show me the ping result, I can check the content and see if the host replyed or not

正如我所说,它非常慢(我需要这样做 255 次)。

我尝试使用带有端口 80 的 TCP 连接来连接它:

import socket
IP = '192.168.1.100'
PORT = 80
tcpsoc = socket(AF_INET, SOCK_STREAM)
tcpsoc.listen(SOMAXCONN)
try:
    tcpsoc.bind(ADDR)
except Exception,ex:
    print "host is down!"

但是,它仍然不适用于此 IP,尽管它适用于路由器 IP

有没有办法更快地获得所有实时 IP?

4

4 回答 4

0

我会使用不同的方法,路由器通常在其 ARP 表中保存所有活动 IP 地址,假设这是一个专业网络并且任何基本的专业路由器都在回答 SNMP 请求,使用 Python 和一些 SNMP 包(如:PySNMP)并获取从它的列表。

提示:ARP 表 OID = 1.3.6.1.2.1.4.22 (ipNetToMediaTable)

获得该列表后,我会使用 ICMP(ping) 或任何其他响应式协议仔细检查它。

于 2013-07-08T11:31:54.357 回答
0

Ping 是询问机器是否已申请 IP 地址的适当方式。它很慢,因为(取决于您的平台)ping 超时通常是一秒。您可以通过减少超时或使用线程模块同时发送多个 ping 来加快速度。

您直接在 python 中实现 ping:Pinging servers in Python

或者,使用类似nmap的工具。

于 2013-07-07T16:17:51.223 回答
0

scapy 提供了一个函数。我不确定这是否是多线程的。如果没有,只需以多线程方式调用不同范围的函数。

>>> arping("192.168.1.*")
于 2013-07-10T18:50:29.520 回答
0

您可以与多处理池ping并行调用:

from multiprocessing.pool import ThreadPool

def ping(host):
    ping = subprocess.Popen(['ping', '-w', '500', host],
                            stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    out, error = ping.communicate()
    return (out, error)
addresses = ['192.168.0.1', '192.168.0.2',] # etc.
pool = Pool(10) # Increase number to increase speed and resource consumption
ping_results = pool.map(ping)
print(ping_results)

pool.close()
pool.join()

或者,使用ctypes调用ICMPSendEchoping方法。

于 2013-07-07T18:54:50.363 回答