Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing commands with sudo using php

I have a script which calls the following command to get the number of unread messages:

sudo ls /var/vmail/username/new | wc -l

This works fine when running from the shell (permissions set up and it's running fine without providing password).

But when running from PHP using exec, it is executed as expected, but it always returns 0.

What may be causing this? How can I debug or fix the issue?

(php 5.3, redhat, apache with ~default config)

EDIT

Thanks ruaks for the tip. The problem is: sudo: sorry, you must have a tty to run sudo. Commenting out the entry in the /etc/sudoers helped:

Defaults            requiretty
Defaults:apache     !requiretty

But looks like this is not so good for security. Any other, better solution?

like image 814
Sfisioza Avatar asked Jul 07 '26 02:07

Sfisioza


2 Answers

When executing PHP through apache, the process is owned by whichever user apache runs as. See: Finding out what user Apache is running as? As mentioned there, it's usually a security risk for that user to be in sudoers.

like image 55
thatwasbrilliant Avatar answered Jul 09 '26 16:07

thatwasbrilliant


It is probably because you did not configure your sudoers. Go to /etc/sudoers and give permission to www-data to execute the script. So vim /etc/sudoers and then insert www-data ALL=(root) NOPASSWD: full/script/path.sh if you waqnt further debugging then when you login as root do su www-data and then once you log in as www-data try to run the script you are running in php and see what error you get

like image 20
Quillion Avatar answered Jul 09 '26 15:07

Quillion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!