简体   繁体   中英

Running “Last” Linux Command

I'm trying to execute a linux command in PHP, here is my sample code:

$command = "last -F";
$o = shell_exec($command);
print_r($o);

Most of the Linux commands gives me an output, but for the Last -F command, I have no output. Why is it so?

Try This Explaination . Your issue MAY be that the last line of last -F is a new-line. shell_exec() only returns the last line of the command, and therefore, if that line is empty, you get nothing, nada.

As an alternative, try exec() , this will allow you to capture the return value (success or failure of execution) as well as the entirety of the command's output. Check it out here

You are executing that command as web user ( nobody or www-data ), which is a limited privileged user.You have to execute that command as root. Unfortunately giving sudo permission or full permission to web user is really a bad idea. So I recommend make a cron or background script that execute last -F and write output to a file. You can read that file from your PHP script.

You can make a script runs in background like this.

   #!/bin/bash

    while [ true ]; do
         last -F > /tmp/myfile
    done

save the code as mycron.sh

chmod +x mycron.sh
mycron.sh &

Read the file /tmp/myfile from your PHP Program. It will give the exact output of that command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM