我在Windows服务器上运行脚本以使用nmap查找设备MAC地址。
$ip= $_SERVER['REMOTE_ADDR'];
$line = "C:\\nmap -sP -n $ip";
echo "You IP address ";
echo $ip;
echo "<br><br>";
$ping = shell_exec("$line");
$mac = substr($ping,156,17);
echo "MAC ADDRESS: ";
echo $mac;
每次运行脚本时,MAC地址输出都会略有不同。我怀疑它是因为该命令增加了时间和延迟信息,这又改变了字符数。是否有更有效的方法来拉取mac地址?
(nmap -sP -n $ip
的原始样本输出)
Starting Nmap 6.46 ( http://nmap.org ) at 2014-07-29 10:00 Central Daylight Time
Nmap scan report for 10.0.0.152
Host is up (0.00s latency).
MAC Address: C8:F6:50:FF:FF:FF (Apple)
Nmap done: 1 IP address (1 host up) scanned in 0.39 seconds
答案 0 :(得分:0)
使用正则表达式:
$str = "Starting Nmap 6.46 ( http://nmap.org ) at 2014-07-29 10:00 Central Daylight Time Nmap scan report for 10.0.0.152 Host is up (0.00s latency). MAC Address: C8:F6:50:FF:FF:FF (Apple) Nmap done: 1 IP address (1 host up) scanned in 0.39 seconds";
preg_match('/MAC Address: ([A-F0-9\:]+)/',$str, $matches);
$mac = $matches[1];
var_dump ($mac);
将输出:
string(17) "C8:F6:50:FF:FF:FF"
答案 1 :(得分:0)
您可以使用多个字符串函数或正则表达式来提取MAC地址:
字符串方法:
$macLookup = 'MAC Address: ';
$pos = strpos($ping, $macLookup);
if ($pos !== false) {
$mac = substr($ping, $pos+strlen($macLookup), 17 );
echo $mac; //C8:F6:50:FF:FF:FF
}
正则表达式方法:
if (preg_match('/MAC Address: ([A-F0-9:]+)/', $ping, $matches)) {
$mac = $matches[1]; //C8:F6:50:FF:FF:FF
}
在线演示here。