我希望你一切安好。跨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)
我已經找了一些信息,但是我發現的東西似乎有點含糊。如果您知道的任何意見或研究途徑,可以幫助我,我將不勝感激
乾杯
克里斯
我很想被證明是錯誤的,但我懷疑你能夠在其他子網中獲得MAC地址。 – NPE 2011-03-02 10:43:19
我運行你的代碼上面,但得到錯誤...'追蹤(最近呼叫最後): 文件「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