【发布时间】:2017-03-07 17:35:55
【问题描述】:
我在寻找这个问题的答案时遇到了问题。所以我想我会与大众分享我建造的东西。 我试图做的是运行 ARP -a 命令并捕获结果以在 TXT 文件中用于稍后的其他内容。经过大量搜索,我能够编译这个。
我在代码中添加了注释,以帮助那些经验不足的人了解每个部分的作用。
但是这段代码做了这些组件
- 设置输出路径(如果需要)
- 查找当前机器IP 地址
- 将 IP 方案分解为仅托管前 3 个 八位字节。 *如果您使用的是具有多个 NIC 或 IP 地址的机器,则其中有一行代码是 # 以允许您过滤 如果需要,只需要一个。
- 捕获 ARP 表。 *我有 2 个版本的 ARP 捕获。第一个是如果您要按设备 IP 方案进行过滤。这将有助于删除 DNS 和环回条目。第二个是如果你想要一切。
- 将 IP 地址的结果输出到 txt 文件。
就我而言,我只是用它来过滤 IP 地址。您可能需要它用于其他目的。好消息是,您可以轻松更改这些部分,以便您根据自己的需要进行更多过滤。
#Captures ARP Table then Displays ALL IPs that match the local computers IP Address
#Set the file you wish for the data to Output to
$OutputPath = "C:\Temp\Test.txt"
#Captures the devices IP Scheme and break it down, remove the Last Octet from the string
#This section is only used IF you are trying to filter the ARP by the local network the device is on.
[string[]]$ComputerName = $env:computername
$OrgSettings = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $ComputerName -EA Stop | ? { $_.IPEnabled }
$ip = $OrgSettings.IPAddress[0]
#IF (!($ip[1] -eq $null)) {$ip = $ip[0]}
$ip = (([ipaddress] $ip).GetAddressBytes()[0..2] -join ".") + "."
$ip = $ip.TrimEnd(".")
#Searches the ARP table for IPs that match the scheme and parses out the data into an Array (It removed the Devices IP from the list.)
Remove-Variable macarray
$macarray = @()
#(arp -a) -match $ip | Foreach{ #Use if needed for filtering results
(arp -a) | Foreach{ #Use this IF no filtering needed
$obj = New-Object PSObject -Property @{
IP = ($_ -split "\s+")[1]
MAC = ($_ -split "\s+")[2]
}
IF (!($obj.MAC -eq "---" -or $obj.MAC -eq "Address" -or $obj.MAC -eq $null -or $obj.MAC -eq "ff-ff-ff-ff-ff-ff")) {$macarray += $obj}
}
#Outputting the IP Addresses captured.
$macarray | Select -ExpandProperty "IP" | Out-file -FilePath $OutputPath -Force
【问题讨论】:
-
我在这里看不到您的问题。到底出了什么问题?
-
Windows8/Server2012 或更高版本具有
Get-NetNeighborcmdlet。 -
这只是您宣传您的代码以供使用吗?如果您为此使用GitHub或其他东西会更合适。
标签: powershell ip mac-address arp