python - 来自 IP 跨网络的 MAC 地址

标签 python network-programming ip-address mac-address

希望你一切都好。

我想知道您是否可以帮助我或为我指明正确的方向。我目前正在从事一个以网络管理为中心的项目。由于严格的时间限制,我尽可能使用开源代码。我遇到的问题是项目的一部分要求我能够捕获连接到网络的所有设备的 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)

我已经查找了一些信息,但我发现的内容似乎有点模糊。如果您知道任何可能对我有帮助的想法或研究途径,我将不胜感激

干杯

克里斯

最佳答案

您不能直接获取子网外机器的 MAC 地址。

网络管理应用程序的一个常见策略是查询确实有此信息的机器,例如连接这些机器的路由器和交换机,使用SNMP .路由器有它们直接连接到的子网的 arp 表(因为它们需要这个来完成它们的工作),并且可以从路由器获取此信息。

this question 的答案可能有助于找到 python 库代码来帮助完成这项工作。

关于python - 来自 IP 跨网络的 MAC 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5166280/

相关文章:

python - argparse 命令行 - 给定路径后的选项

c++ - QTcpSocket的write()方法为什么不能发送数据?

java - 基于证书和IP的认证

java - 连接到3G移动网络时获取android设备的IP地址

java - Java如何从域名中获取IP地址?

python - 为什么start_transaction不设置事务隔离级别?

python - pytest 参数化 fixture - 来自 json 的参数?

python - tfidf 上的 scikit-learn NearestNeighbors .kneighbors() 给出 ValueError : UPDATEIFCOPY base is read-only

计算接收/发送数据的时间以计算带宽

java - 如何检查用户意外终止连接