bash 在 PHP 中解析 Linux 命令 'who' 的输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2169778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing the output of Linux command 'who' in PHP
提问by ZeroUptime
I've tried parsing a list of users currently connected via SSH to a server, but the results are very irregular, so I was forced to simply do:
我试过解析当前通过 SSH 连接到服务器的用户列表,但结果非常不规则,所以我被迫简单地做:
$users = shell_exec('who');
echo "<pre>$users</pre>";
Is there a better way to parse the output of whoin the command line before I let PHP mess around with it? I want it in an array which contains the username (first column below), the terminal they're connected on (second column), the date and time they connected (third), and the IP from where they connected (in parenthesis). I'm guessing I should use preg_splitto split the data but it seems really irregular sometimes with username length, terminal name, etc..
who在我让 PHP 处理它之前,有没有更好的方法来解析命令行中的输出?我希望它包含在一个数组中,其中包含用户名(下面的第一列)、他们连接的终端(第二列)、他们连接的日期和时间(第三)以及他们连接的 IP(在括号中)。我猜我应该preg_split用来分割数据,但有时用户名长度、终端名称等似乎真的不规则。
(some example output of who):
(一些示例输出who):
alex tty7 2010-01-23 17:04 (:0)
alex pts/0 2010-01-30 17:43 (192.168.1.102)
root pts/1 2010-01-30 17:45 (192.168.1.102)
回答by Douwe Maan
explode()ing on newlines (\n) gives you an array with one item per line, and when you loop through the array, and use preg_split("/\s+/", $sValue, 3), it should give you a new array with every column as an item. Then you need to split the Date and the Addr.
explode()使用换行符 ( \n) 为您提供一个每行一个项目的数组,当您遍历该数组并使用 时preg_split("/\s+/", $sValue, 3),它应该为您提供一个每列作为一个项目的新数组。然后你需要拆分日期和地址。
The full code would be something like this:
完整的代码是这样的:
<?php
$sTempUsers = shell_exec('who');
$aTempUsers = explode("\n", $sTempUsers);
$aUsers = array();
foreach($aTempUsers AS $sUser)
{
$aTempUser = preg_split("/\s+/", $sUser, 3); // username | terminal | date addr
preg_match("/^(.+)\s\((.+)\)$/", $aTempUser[2], $aDateAndAddr); // full match | date | addr
$aUsers[] = array(
$aTempUser[0],
$aTempUser[1],
$aDateAndAddr[1],
$aDateAndAddr[2]
); // username | terminal | date | addr
}
?>
You can find the result in $aUsers.
您可以在 中找到结果$aUsers。
回答by Tobias Cohen
preg_splitonly needs to match the space between the data, not the data itself:
preg_split只需要匹配数据之间的空间,而不是数据本身:
$who = shell_exec('who');
$users = array();
foreach(split("\n", $who) as $user) {
$users[] = preg_split("/\s{2,}/", $user); //Match 2 or more whitespace chars
}
回答by ghostdog74
$who = shell_exec('who');
$s = split("\n",$who);
$func = function($value) { return preg_split("/\s{2,}/",$value ); };
print_r(array_map($func, $s));

