使用 python 3 in Windows 枚举连接到我的路由器的设备

Enumerate devices connected to my router using python 3 in Windows

我正在尝试编写一个脚本来检查有多少设备连接到互联网。这是一个更大项目的一部分,目的是向我的 ISP 证明我的互联网很糟糕。我每分钟执行一次速度测试,并将其记录到一个文本文件中。 我想同时记录连接了多少设备,只是为了确保问题不是只有在连接了一定数量的设备后互联网才会变得糟糕。 这个网络上没有多人流式传输,所以我知道这不是问题所在,但如果是设备问题,我可能需要升级我的互联网。 我尝试使用模块 neighbourhoodlanscan,但我无法让它们在我的机器上工作。

使用 lanscan 我尝试 lanscan.lanscan.networks() 并收到错误消息

"module 'lanscan' has no attribute 'lanscan'"

My python IDE 建议这些模块应该以这种结构存在。 lanscan.networks() 除了说“'networks' 不存在”之外,给出相同的错误。此外,neighbourhood 使用的函数在 windows 中不起作用,例如 os.geteuid(),因此我认为它与 windows.

不兼容

有什么方法可以找到我的哪些设备当前连接到我的 Internet 网络?实际上,我真正需要的只是设备的数量。我知道,如果我连接 router/modem 的 IP 地址,我可以看到连接的设备的名称及其 IP 地址,所以我觉得我应该能够以某种方式找到这些信息。

Neighborhood Lanscan

我找到了一个答案,但似乎不是 100% 准确。我注意到所有连接到我的路由器的设备都有直截了当的名称。我的ip地址是192.168.0.1,所以我的设备是192.168.0.10, 192.168.0.11, 192.168.0.1 2,等等。因此我只对前 10 个设备执行 ping 操作。不过,我不一定只相信回应。一旦 ping 我 运行 arpa -a 通过 windows 系统与子进程。

import subprocess

#this for loop depends on ho wlong you are willing to wait. I am
for i in range(10):   #look for up to 10 devices
    command=['ping', '-n', '1', '192.168.0.1'+str(i)]   #icrement the device names
    subprocess.call(command)   #ping the devices to update data before  "arp -a'

arpa = subprocess.check_output(("arp", "-a")).decode("ascii") #call 'arp -a' and get results

#I count lines that contain 192.1868, but not ['192.168.0.1 ','192.168.0.255'] 
#because those are the router and broadcast gateway. Note that the machine 
#you are running the code from will get counted because it will be in the 
#first line "Interface: 192.168.0.10 --- 0x4" in my case
n_devices=len([x for x in arpa.split('\n') if '192.168' in x and  all(y not in x for y in ['192.168.0.1 ','192.168.0.255']) ])

第二种方式是这样,比较慢。这会检查从 0 到 255 的所有 ip。我切换到 xfinity 路由器,发现它们在分配动态 ip 时使用相当随机的数字,这与摩托罗拉不同,摩托罗拉仅使用从 192.168.0.10 开始的序列号(在我的模型中)。那么这个答案更笼统。我查看了所有 255 种可能性,但我将响应时间限制为 100 毫秒(使用参数“-w”和“100”,所以它不会永远持续下去。应该需要大约 25 秒来 ping 一切,但如果发现它需要更像是一分钟。

for i in range(255):
    command=['ping', '-n', '1','-w','100', '10.0.0.'+str(i)]
    subprocess.call(command)

arpa = subprocess.check_output(("arp", "-a")).decode("ascii")
n_devices=len([x for x in arpa.split('\n') if '10.0.0.' in x and  
    all(y not in x for y in ['10.0.0.1 ','10.0.0.255']) ])