跨IP网络的IP地址

问题描述:

我希望你一切安好。跨IP网络的IP地址

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

我已经找了一些信息,但是我发现的东西似乎有点含糊。如果您知道的任何意见或研究途径,可以帮助我,我将不胜感激

干杯

克里斯

+3

我很想被证明是错误的,但我怀疑你能够在其他子网中获得MAC地址。 – NPE 2011-03-02 10:43:19

+0

我运行你的代码上面,但得到错误...'追踪(最近呼叫最后): 文件“Get_MacAddress_from_ip.py”,行26,在 mac = re.search(r“([a-fA-F0 -9] {2} [:| \ - ]?){6}“,s)。组()[0] AttributeError的:“NoneType”对象有没有属性“组” ' – Fahadkalis 2015-02-16 20:40:55

不能直接得到一台机器的MAC地址,子网之外。

用于网络管理应用的常用策略是查询机器,具有此信息,如路由器和交换机连接的机器,使用SNMP。路由器为它们直接连接的子网提供ARP表(因为他们需要这些工作来完成他们的工作),并且可以从路由器获取这些信息。

this question的答案可能会帮助找到Python库代码在此方面提供协助。

+0

干杯您的答复和建议。这听起来像它可能正是我一直在寻找。 – Lipwig 2011-03-02 13:05:38

,如果你没有连接到同一个你不能得到主机的原始MAC地址子网 - 您只需获取最后一台路由器的MAC地址。

只有这样,才能让所有的M​​AC地址将设置一个服务器,以赶上他们在每个子网,但是这在我看来有点疯狂的想法。还需要注意的是,现在伪造MAC地址非常容易,而且根本不可靠。总之,我认为你应该采用不同的方法;例如,有大量的网络库存系统,您可以使用其中的一个,并与其进行交互。

+0

感谢您的快速回应,我将不得不考虑网络库存系统 – Lipwig 2011-03-02 13:06:26