首页 > 解决方案 > 过滤掉 PHP shell_exec 输出结果

问题描述

我正在尝试使用 php 创建一种在我的网络上查找 Raspberry pi 的方法,我想知道如何过滤结果以便我只能看到一台特定计算机的 IP 地址?

<?php
$output = shell_exec('sudo arp-scan --localnet');
echo "<pre>$output</pre>";
?>

这是执行 php 代码时的输出示例。

Interface: wlan0, datalink type: EN10MB (Ethernet)
Starting arp-scan 1.9.5 with 256 hosts (https://github.com/royhills/arp-scan)

192.168.1.62    b8:29:0b:ed:e0:27   Raspberry Pi Foundation
192.168.1.95    14:6b:00:00:ec:59   (Unknown)
192.168.1.72    24:46:11:00:ee:3f   (Unknown)


15 packets received by filter, 0 packets dropped by kernel
Ending arp-scan 1.9.5: 256 hosts scanned in 3.722 seconds (68.78 hosts/sec). 15 responded

我正在尝试找到一种方法来过滤所有文本,但在这种情况下保留 Raspberry Pi Foundation 的 IP 地址 192.168.1.62

标签: phplinuxraspberry-pishell-exec

解决方案


preg_match_all 最适合这些类型的问题

<?php
$text = 'Interface: wlan0, datalink type: EN10MB (Ethernet)
Starting arp-scan 1.9.5 with 256 hosts (https://github.com/royhills/arp-scan)

192.168.1.62    b8:29:0b:ed:e0:27   Raspberry Pi Foundation
192.168.1.95    14:6b:00:00:ec:59   (Unknown)
192.168.1.72    24:46:11:00:ee:3f   (Unknown)


15 packets received by filter, 0 packets dropped by kernel
Ending arp-scan 1.9.5: 256 hosts scanned in 3.722 seconds (68.78 hosts/sec). 15 responded
';
$regMatch = '/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\ \ \ (.*)\ \ \ (.*)/';
preg_match_all( $regMatch, $text, $out, PREG_PATTERN_ORDER);
print_r($out);

print_r($out[2]);  #vendor array


推荐阅读