使用shell脚本无法正常运行mkdir

max*_*sme 5 php bash shell tty ubuntu-14.04

我创建了一个如下所示的文件test.sh:

#!/bin/sh
mkdir /testDir
Run Code Online (Sandbox Code Playgroud)

如果我在命令行上运行脚本,如:sudo /path/to/test.sh它成功创建了目录.

我在以下位置添加了这样的sudo权限visudo:

www-data ALL=NOPASSWD: /path/to/test.sh
Run Code Online (Sandbox Code Playgroud)

我在.php文件中运行这样的脚本:

shell_exec('sh /path/to/test.sh');
Run Code Online (Sandbox Code Playgroud)

但是没有创建目录!

我究竟做错了什么?!


正确的用户sudo权限?

当我运行shell_exec('whoami')php文件时,我得到:

www-data
Run Code Online (Sandbox Code Playgroud)

正确的PHP脚本路径?

我通过添加一个echo语句来测试shell脚本,如:

#!/bin/sh
mkdir /testDir
echo "hello"
Run Code Online (Sandbox Code Playgroud)

当我运行.php命令时:

echo shell_exec('sh /path/to/test.sh');
Run Code Online (Sandbox Code Playgroud)

.php页面返回

你好

我也试过test.sh:

output=$( mkdir /testDir )
echo "$output"
Run Code Online (Sandbox Code Playgroud)

但没有任何回报


更新

如果我将其添加到visudo:

www-data ALL=(ALL) NOPASSWD: ALL
Run Code Online (Sandbox Code Playgroud)

有用!!但当我这样做时:

www-data ALL=(ALL) NOPASSWD: /path/to/test.sh
Run Code Online (Sandbox Code Playgroud)

它不......正如你所知道的那样.


通过将PHP更改为,我找到了一种很好的调试方法

echo shell_exec('sh /path/to/test.sh  2>&1 1> /dev/null');
Run Code Online (Sandbox Code Playgroud)

并返回错误:

sudo:没有tty存在且没有指定askpass程序

所以我试过了:

  • 添加Defaults:www-data !requirettyvisudo,但没有运气!!!!

  • 添加-t-Asudo命令...(即sudo -t ...)

  • export SUDO_ASKPASS=/usr/lib/openssh/gnome-ssh-askpass在sudo命令之前添加,然后只会导致一个全新的错误世界.

我不知道这个,requiretty因为它似乎不在我的ubuntu系统的任何地方.它没有提到一次visudo


我花了太长时间!

有人能告诉我,如果我这样做,我会遇到什么问题:

www-data ALL=(ALL) NOPASSWD: ALL
Run Code Online (Sandbox Code Playgroud)

Sig*_*uza 1

如果

www-data ALL=(ALL) NOPASSWD: ALL
Run Code Online (Sandbox Code Playgroud)

有效,但是

www-data ALL=(ALL) NOPASSWD: /path/to/test.sh
Run Code Online (Sandbox Code Playgroud)

不,那么显然执行的命令不匹配/path/to/test.sh
看看你的代码,你实际上没有调用/path/to/test.sh

sh /path/to/test.sh
Run Code Online (Sandbox Code Playgroud)

你正在调用sh!作为/path/to/test.sh第一个论点,但仍然如此。
您需要直接调用脚本(如果有效):

shell_exec('/path/to/test.sh');
Run Code Online (Sandbox Code Playgroud)

或相应地更新您的 sudoers 文件(注意 的完整路径sh):

www-data ALL=(ALL) NOPASSWD: /bin/sh /path/to/test.sh
Run Code Online (Sandbox Code Playgroud)