简体   繁体   English

运行“最后”Linux命令

[英]Running “Last” Linux Command

I'm trying to execute a linux command in PHP, here is my sample code: 我正在尝试用PHP执行linux命令,这是我的示例代码:

$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. 大多数Linux命令给我一个输出,但对于Last -F命令,我没有输出。 Why is it so? 为什么会这样?

Try This Explaination . 试试这个解释 Your issue MAY be that the last line of last -F is a new-line. 您的问题可能是最后一行last -F的最后一行是换行符。 shell_exec() only returns the last line of the command, and therefore, if that line is empty, you get nothing, nada. shell_exec()只返回命令的最后一行,因此,如果该行为空,则什么也得不到,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. 作为替代方法,尝试使用exec() ,这将允许您捕获返回值(执行的成功或失败)以及命令输出的全部内容。 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. 您正在以web用户( nobodywww-data )执行该命令,该用户是有限的特权用户。您必须以root身份执行该命令。 Unfortunately giving sudo permission or full permission to web user is really a bad idea. 不幸的是,给网络用户提供sudo权限或完全权限是一个坏主意。 So I recommend make a cron or background script that execute last -F and write output to a file. 因此,我建议创建一个执行last -F的cron或后台脚本,并将输出写入文件。 You can read that file from your PHP script. 您可以从PHP脚本中读取该文件。

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 将代码保存为mycron.sh

chmod +x mycron.sh
mycron.sh &

Read the file /tmp/myfile from your PHP Program. 从PHP程序中读取文件/tmp/myfile It will give the exact output of that command. 它将给出该命令的确切输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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