PHP trim nmap MAC address

2019-06-09 22:35发布

I am running a script on a windows server to find device MAC address with nmap.

$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;

The MAC address output varies a little each time the scripted is run. I suspect it because the command adds time and latency information which in turn changed the character count. Is there a more effective way to pull just the mac address?

(original sample output of 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

标签: php windows nmap
2条回答
我命由我不由天
2楼-- · 2019-06-09 23:15

You can either use several string functions or a regular expression to pull out the MAC address:

String method:

$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
}

Regex method:

if (preg_match('/MAC Address: ([A-F0-9:]+)/', $ping, $matches)) {
     $mac = $matches[1]; //C8:F6:50:FF:FF:FF
}

Online demo here.

查看更多
Emotional °昔
3楼-- · 2019-06-09 23:18

Using a regular expression:

$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);

will output:

string(17) "C8:F6:50:FF:FF:FF"
查看更多
登录 后发表回答