php - 无法在 PHP 脚本中运行 Linux "awk"命令

标签 php linux awk pid cut

我有 shell 脚本“test.sh”:

  #!/system/bin/sh

  PID=$(ps | grep logcat | grep root |grep -v grep | awk '{print $2}')
  echo "Using awk: $PID"


  PID=$(ps | grep logcat | grep root |grep -v grep | cut -d " " -f 7 )
  echo "Using cut: $PID"

当我从 PHP 运行脚本时:

exec("su -c sh /path/to/my/script/test.sh");

我得到了这个输出:

Using awk:
Using cut: 6512  

所以当我从 PHP 运行脚本时,“cut”命令有效,但是当我从终端运行脚本时,“awk”命令无效:

# sh test.sh

我可以让 awk 和 cut 工作得很好!这看起来像“ps”的输出:

USER      PID   PPID  VSIZE  RSS   WCHAN       PC         NAME
root      6512  5115  3044   1108  poll_sched b6e4bb0c S logcat

我错过了什么吗?

最佳答案

你应该先学会如何调试

你说

So "cut" command is work but "awk" command doesn't when I run the script from PHP, but when I run it from terminal:

我想知道怎么办?

实际上在 CLI 中抛出如下错误

$ php -r 'exec("su -c sh /path/to/my/script/test.sh");'
su: user /path/to/my/script/test.sh does not exist

调试代码时首先需要以下语法

// basic :  stdin (0) stdout (1) stderr (2)

exec('your_command 2>&1', $output, $return_status);

// to see the response from your command
// su: user /path/to/my/script/test.sh does not exist
print_r($output);  

Remember :

  • su gives you root permissions but it does not change the PATH variable and current working directory.

  • The operating system assumes that, in the absence of a username, the user wants to change to a root session, and thus the user is prompted for the root password

[akshay@localhost Desktop]$ su
Password: 
[root@localhost Desktop]# pwd
/home/akshay/Desktop
[root@localhost Desktop]# exit
exit

[akshay@localhost Desktop]$ su -
Password: 
[root@localhost ~]# pwd
/root

解决方法:

你应该允许在没有密码提示的情况下执行你的脚本(不要使用 su 使用 sudo )

要允许 apache 用户执行您的脚本和一些命令,您可以在 /etc/sudoers 中进行如下输入

# which awk => give you awk path
# same use in your script also, or else set path variable 
www-data ALL=NOPASSWD: /path/to/my/script/test.sh, /bin/cut, /usr/bin/awk

所以它变成了:

// assuming your script is executable 
exec("sudo /path/to/my/script/test.sh 2>&1", $output);
print_r($output);  

关于php - 无法在 PHP 脚本中运行 Linux "awk"命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47260838/

相关文章:

linux - Linux 中的 cakephp 热插拔驱动程序是否与 Windows 中的设备禁用/启用功能相同?

linux - 同时执行 awk 和 sed 命令

php - MySQL (InnoDB) 的交易和订单安全

php - 使用php和jquery进行实时通知

linux - 等待子shell进程完成

sed - AWK - 具有不相等字段的过滤器文件

git commit 触发器阻止字节顺序标记

php - 尝试将多行插入 MySQL 表

php - 将一系列父子关系转化为层次树?

linux - cat `-q` 文件(在 linux 中)- 传递看起来像选项的操作数