简体   繁体   中英

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?

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.

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

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

Yes, that is a security risk. I don't know how dynamic this information needs to be; if you're just using it once in a while, and don't mind that it might be slightly outdated, you could opt for writing a cronjob that will execute the command and write the output into a temporary file apache can read.

If you desperately need this information to be 100% accurate and in real-time, you may want to go for another way to determine the number of new messages. If the mailbox is readable using - for example - imap or whatever, PHP has functions that can do the calculation without needing sudo. All in all, that seems to me like the most reusable and "cleanest" way to work anyway.

Adding apache to the sudo'ers file is a security risk, but then, if you add that it can only execute the command you want it to be able to execute like Quillion described, the risks lessen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM