VBScript:获取指定IP地址的MAC地址(仅)

时间:2014-11-24 21:56:33

标签: vbscript

我需要编写一个小脚本,我可以使用 特定IP地址的MAC地址。所以,你可以使用像

这样的东西
arp -a 192.168.x.x | FIND "192.168.x.x"

但你的结果仍然如下:

Interface: 192.168.x.x --- 0x10
   192.168.x.x             00-00-00-00-00-00     dynamic  

不知何故,使用REGEX或其他高级解析方法,我想把它简化为“00-00-00-00-00-00”。我可以使用以下内容,但我想要更清洁的东西:

set obj_exec = obj_shell.Exec("%comspec% /C arp -a 192.168.x.x | FIND "192.168.x.x" > c:\temp\tmp_gatewayMAC.txt")
set obj_FSO = createobject("Scripting.FileSystemObject")
set obj_file = obj_FSO.opentextfile("c:\temp\tmp_gatewayMAC.txt", 1)
do until obj_file.AtEndOfStream
    str_line = obj_file.readline
    if instr(str_line, "dynamic") > 0 then
        str_MACaddress = str_line
    end if
loop

str_MACaddress = replace(str_MACaddress, "dynamic","")
str_MACaddress = replace(str_MACaddress, "192.168.x.x","")
str_MACaddress = replace(str_MACaddress, " ","")
str_MACaddress = trim(str_MACaddress)
vbscript.echo(str_MACaddress)

目前,忽略我们如何确定网关IP地址,因为我将为此提出一个与此不同的方法。理想情况下,我可以运行(但无法找到)像ARP这样的其他实用程序但只返回MAC。

2 个答案:

答案 0 :(得分:2)

Option Explicit

Dim IP
    IP = "192.168.1.1"

Dim getMACCommand
    getMACCommand = """%comspec%"" /q /c ""for /f ""skip=3 tokens=2"" %a in ('arp -a "& IP &"') do echo %a"""

Dim strMACAddress    
    strMACAddress = WScript.CreateObject("WScript.Shell").Exec(getMACCommand).StdOut.ReadAll

    WScript.Echo strMACAddress

是的,它可以使用正则表达式完成,但由于数据是从生成的cmd实例中检索的,所以让它来完成工作

答案 1 :(得分:0)

比简单解析器多一些代码但是它使用WMI来查找具有特定IP地址的网络适配器的mac地址。由于它使用WMI,因此ip地址将存储在一个数组中,我们需要检查ip是否在该特定适配器的列表中。

Option Explicit

Dim objWMIService, colItems, objItem
Dim strQuery, strIP, strMAC, strIPAddressToLocate

strIPAddressToLocate = "169.244.119.133"
strMAC = ""

strQuery = "SELECT * FROM Win32_NetworkAdapterConfiguration"
Set objWMIService = GetObject( "winmgmts://./root/CIMV2" )
Set colItems      = objWMIService.ExecQuery( strQuery, "WQL", 48 )

For Each objItem in colItems
    ' Ensure this adapter has at least one IP by checking if the value is an array. Filter out null/empty
    If IsArray( objItem.IPAddress ) Then
        If UBound( objItem.IPAddress ) = 0 Then
            ' Only one ip. Return that.
            strIP = objItem.IPAddress(0)
        Else
            ' Multiple IP's. Concat them so we can check contents with instr.
            strIP = Join( objItem.IPAddress, "," )
        End If

        If InStr(strIP,strIPAddressToLocate) <> 0 Then
            ' Get the mac address of the adapter matching this ip address. 
            strMAC = objItem.MacAddress
            ' Found the MAC we are looking for. Stop checking the loop
            Exit For
        End If
    End If
Next

If strMAC <> "" Then
    MsgBox "The IP Address: " & strIPAddressToLocate & " appears to be assigned to the adapter with the MAC Address: " & strMAC
Else
    MsgBox "Unable to locate a network adapater with the Ip Address: " & strIPAddressToLocate
End If