Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running mkdir through php using shell script not working

I have created a file test.sh which looks like this:

#!/bin/sh
mkdir /testDir

If I run the script on the command line like: sudo /path/to/test.sh it successfully creates the directory.

I have added the sudo permissions like this in the visudo:

www-data ALL=NOPASSWD: /path/to/test.sh

and I am running the script like this in my .php file:

shell_exec('sh /path/to/test.sh');

But no directory is being created!

What am I doing wrong?!


Correct user for sudo permissions?

When I run shell_exec('whoami') on the php file I get:

www-data

Correct path to script from php?

I have tested the shell script by adding an echo statement like:

#!/bin/sh
mkdir /testDir
echo "hello"

And when I run the .php command like:

echo shell_exec('sh /path/to/test.sh');

the .php page returns

hello

I have also tried in the test.sh:

output=$( mkdir /testDir )
echo "$output"

but nothing is returned


Update

If I add this to the visudo:

www-data ALL=(ALL) NOPASSWD: ALL

it works!! But when I do:

www-data ALL=(ALL) NOPASSWD: /path/to/test.sh

It doesn't... As you know already know.


I have found a good way to debug by also changing the PHP to

echo shell_exec('sh /path/to/test.sh  2>&1 1> /dev/null');

and it returns the error:

sudo: no tty present and no askpass program specified

So I have tried:

  • adding Defaults:www-data !requiretty to the visudo but no luck!!!!

  • adding -t and -A to the sudo command... (ie sudo -t ...)

  • adding export SUDO_ASKPASS=/usr/lib/openssh/gnome-ssh-askpass before the sudo command and that then just leads to a whole new world of errors.

I have no idea about this requiretty as it does not seem to be anywhere on my ubuntu system. It is not mentioned once in the visudo?


I have spent too long on this!

Can someone tell me what the problems that I could come across if I did just do:

www-data ALL=(ALL) NOPASSWD: ALL

?

like image 814
maxisme Avatar asked Nov 10 '22 14:11

maxisme


1 Answers

If

www-data ALL=(ALL) NOPASSWD: ALL

works, but

www-data ALL=(ALL) NOPASSWD: /path/to/test.sh

does not, then clearly the executed command does not match /path/to/test.sh.
And looking at your code, you are actually not invoking /path/to/test.sh:

sh /path/to/test.sh

You are invoking sh! With /path/to/test.sh as first argument, but still.
You either need to invoke the script directly (if that works):

shell_exec('/path/to/test.sh');

or update your sudoers file accordingly (note the full path of sh):

www-data ALL=(ALL) NOPASSWD: /bin/sh /path/to/test.sh
like image 76
Siguza Avatar answered Nov 14 '22 22:11

Siguza