从txt文件中提取IP地址和PC名称

时间:2017-01-16 18:21:44

标签: php

我目前有这个代码,它作为PHP脚本运行,让我知道PC是否正在ping:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="30">
</head>
<body>

<h1>PC Test Ping Status</h1>

<?php
$host="10.191.10.98";
exec("ping -c 2 " . $host, $output, $result);
if ($result == 0)
echo "<p>p2 On-Line</p>";
else
echo "<p>p2 Off-Line !</p>";

$host="10.191.10.125";
exec("ping -c 2 " . $host, $output, $result);
if ($result == 0)
echo "<p>p3 On-Line</p>";
else
echo "<p>p3 Off-Line!</p>";

?> 


</body>
</html>

我想从txt文件中的列中提取PC名称和地址数据,而不是:

pc1 10.191.10.1
pc2 10.191.10.2
pc3 10.191.10.3
pc4 10.191.10.4

依此类推......所以我们可以添加到列表中,它会继续运行。

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

<?php
$file = file_get_contents('textfile.txt');    //Replace with full path to the file.
$lines = explode("\n", $file);     //Might have to use \r\n depending on your system.
foreach($lines as $pingTarget) {
    $pcs = explode(' ',$pingTarget);
    $host=$pcs[1];
    exec("ping -c 2 " . $host, $output, $result);
    if ($result == 0)
        echo "<p>".$pcs[0]." On-Line</p>";
    else
        echo "<p>".$pcs[0]." Off-Line !</p>";
}
?>

通过这种方式,您将提取文本文件的内容,然后遍历每一行,为每个系统提供输出。

根据您的超时时间,您可能需要在循环内设置一个时间限制,以便让每个系统都能响应,特别是如果您有一长串要ping的PC:

set_time_limit(5);   //Set time in seconds

答案 1 :(得分:0)

您可以使用RegEx查询提取IP,然后将它们添加到数组中。此外,不是您手动添加主机名,而是让PHP使用gethostbyaddr($v)为您解析主机名。在我的示例中,我使用Google DNS显示DNS解析和您无法解析的私有IP,因为它们不在我的LAN上。它很方便,因为如果您重命名PC或您的IP使用DHCP(每X天获取一个新的IP地址),则无需更新文本文件。

$ipLst = file_get_contents('ip.txt'); 
preg_match_all('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $ipLst, $ipArr); //Match an IP and add to ipArr Array

foreach($ipArr[0] as $k=>$v) { //Loop through ipArr

    $hostname = gethostbyaddr($v); //Reverse lookup to resolve hostname

    exec("ping -c 2 " . $v, $output, $result);

    if ($result === 0) {
        echo "<p>$hostname is On-Line!</p>"; //Echo Hostname or IP if its unable to resolve

    }else{
        echo "<p>$hostname is Off-Line!</p>"; //Echo Hostname or IP if its unable to resolve
    }

}

文字档案:

pc1 8.8.8.8
pc2 10.191.10.2
pc3 10.191.10.3
pc4 10.191.10.4

<强>输出:

google-public-dns-a.google.com is On-Line!

10.191.10.2 is Off-Line!

10.191.10.3 is Off-Line!

10.191.10.4 is Off-Line!