2011-03-02 153 views
1

我希望你一切安好。跨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

回答

3

不能直接得到一臺機器的MAC地址,子網之外。

用於網絡管理應用的常用策略是查詢機器,具有此信息,如路由器和交換機連接的機器,使用SNMP。路由器爲它們直接連接的子網提供ARP表(因爲他們需要這些工作來完成他們的工作),並且可以從路由器獲取這些信息。

this question的答案可能會幫助找到Python庫代碼在此方面提供協助。

+0

乾杯您的答覆和建議。這聽起來像它可能正是我一直在尋找。 – Lipwig 2011-03-02 13:05:38

2

,如果你沒有連接到同一個你不能得到主機的原始MAC地址子網 - 您只需獲取最後一臺路由器的MAC地址。

只有這樣,才能讓所有的M​​AC地址將設置一個服務器,以趕上他們在每個子網,但是這在我看來有點瘋狂的想法。還需要注意的是,現在僞造MAC地址非常容易,而且根本不可靠。總之,我認爲你應該採用不同的方法;例如,有大量的網絡庫存系統,您可以使用其中的一個,並與其進行交互。

+0

感謝您的快速回應,我將不得不考慮網絡庫存系統 – Lipwig 2011-03-02 13:06:26