【问题标题】:Can't run Linux "awk" command in script from PHP无法在 PHP 脚本中运行 Linux“awk”命令
【发布时间】:2018-04-25 22:18:02
【问题描述】:

我有 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  

所以“cut”命令是有效的,但是当我从 PHP 运行脚本时“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

我错过了什么吗?

【问题讨论】:

    标签: php linux awk pid cut


    【解决方案1】:

    你应该先学习如何调试

    你说

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

    我想知道怎么做?

    实际上在 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);  
    

    记住

    • su 为您提供 root 权限,但不会更改 PATH 变量和当前工作目录。

    • 操作系统假定,在没有用户名的情况下, 用户想要更改为 root 会话,因此会提示用户 用于root密码

    [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);  
    

    【讨论】:

    • 感谢回复,$output 和$return_status 的输出分别是"Array" 和"0" 表示没有问题!我忘了提到我正在使用 Android Linux(我通过 SSHelper 应用程序 ssh 到 android),没有 sudo 命令只有 su。对于 PHP,我使用的是 KSWEB 应用程序。
    猜你喜欢
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2023-03-06
    相关资源
    最近更新 更多