从IP到n的MAC地址

2024-05-18 07:53:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望你一切都好。

我想知道你是否能帮我或指引我正确的方向。我目前正在做一个以网络管理为中心的项目。由于严格的时间限制,我尽可能使用开源代码。我遇到的问题是,项目的一部分要求我能够捕获连接到网络的所有设备的MAC地址。

我在网络编程方面的知识是有限的,因为我在过去4年里一直在软件工程的其他领域工作。我所采取的方法是使用nmap作为基础来获取我需要的ip地址和其他信息。MAC地址不包括在nmap输出中,从我所读到的来看,它似乎有点模糊。(我可能错了)。

因此,我尝试用两个阶段的方法来实现这一点,首先,我从nmap获取包括ip地址在内的数据,这样可以很好地工作。我的下一步,也是我遇到困难的地方是ping ip地址(在我的python程序中)。但是如何从IP地址中获取MAC地址呢?我最初认为ping ip并从ARP中获取MAC,但我认为只有当ip地址在同一个子网上时,这才有效。为了解决部署问题,网络上可能有多达5000台计算机需要记录。为了向您展示我的python ping方法,下面是代码:

import pdb, os
import subprocess
import re
from subprocess import Popen, PIPE

# This will only work within the netmask of the machine the program is running on cross router MACs will be lost
ip ="192.168.0.4"

#PING to place target into system's ARP cache 
process = subprocess.Popen(["ping", "-c","4", ip], stdout=subprocess.PIPE)
process.wait()

result = process.stdout.read()
print(result)

#MAC address from IP
pid = Popen(["arp", "-n", ip], stdout=PIPE)
s = pid.communicate()[0]

# [a-fA-F0-9] = find any character A-F, upper and lower case, as well as any number
# [a-fA-F0-9]{2} = find that twice in a row
# [a-fA-F0-9]{2}[:|\-] = followed by either a ?:? or a ?-? character (the backslash escapes the hyphen, since the  # hyphen itself is a valid metacharacter for that type of expression; this tells the regex to look for the hyphen character, and ignore its role as an operator in this piece of the expression)
# [a-fA-F0-9]{2}[:|\-]? = make that final ?:? or ?-? character optional; since the last pair of characters won't be followed by anything, and we want them to be included, too; that's a chunk of 2 or 3 characters, so far
# ([a-fA-F0-9]{2}[:|\-]?){6} = find this type of chunk 6 times in a row

mac = re.search(r"([a-fA-F0-9]{2}[:|\-]?){6}", s).groups()[0] #LINUX VERSION ARP
mac = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", s).groups()[0] #MAC VERSION ARP
print(mac)

我已经找了一些资料,但我发现的似乎有点模糊。如果你知道任何有助于我的想法或研究途径,我会很高兴

干杯

克里斯


Tags: ofthe方法importip网络thatmac