Parsing Linux Who's output in PHP

I tried to parse the list of users connected via SSH to the server, but the results are very irregular, so I was forced to just do:

$users = shell_exec('who');
echo "<pre>$users</pre>";

Is there a better way to parse the output whoon the command line before I let PHP get confused with it? I want it in an array that contains the username (first column below), the terminal to which they are connected (second column), the date and time they connected (third), and the IP from where they were connected (in brackets). I suppose I should use preg_splitto separate the data, but sometimes it seems irregular with the length of the username, terminal name, etc.

(sample output 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)
+3
source share
3 answers

explode()ing for new rows ( \n) gives you an array with one element per row, and when you loop the array and use it preg_split("/\s+/", $sValue, 3), it should give you a new array with each column as an item. Then you need to separate the date and Addr.

The full code will look 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
}
?>

The result can be found in $aUsers.

+4
source

preg_split you only need to combine the space between the data, and not the data itself:

$who = shell_exec('who');
$users = array();
foreach(split("\n", $who) as $user) {
  $users[] = preg_split("/\s{2,}/", $user); //Match 2 or more whitespace chars
}
0
source
$who = shell_exec('who');
$s = split("\n",$who);
$func = function($value) { return preg_split("/\s{2,}/",$value ); };
print_r(array_map($func, $s));
0
source

Source: https://habr.com/ru/post/1730703/


All Articles