How to call shell script from php that requires SUDO?

眉间皱痕 提交于 2019-11-26 00:55:01

问题


I have a file that is a bash script that requires SUDO to work.

I can run it from the command line using SUDO but I will be prompted to put in the SUDO password.

I want to run this script from php via shell_exec but I if I call SUDO, its not like a command line where I can be prompted for the password. Is there a way to pass the password for sudo with the sudo call?

How can I do this?


回答1:


Edit the sudoers file (with visudo) and add a rule that allows the web server user to run the command without a password. For example:

www-data ALL=NOPASSWD: /path/to/script



回答2:


There are various solutions for this problem.

  • First of all, consider changing the script permissions, if reason why you want sudo is simply a permission issue (see the comment I added to the question above).

  • Another approach would be using the setuid bit. [Edit: Looks like setuid does not work well with scripts. For explananations, see this link.]

  • A third, but very insecure method is to read the password from a password file. Warning: This is very insecure, if there's any other possibility, don't do it. And if you do it, try hiding the password file somewhere in your folder hierarchy.

    <?php
    shell_exec('sudo -u root -S bash script.sh < /home/[user]/passwordfile');
    ?>
    
  • And a fourth possibility is to use the NOPASSWD tag in the sudoers file. You should limit this power to the specific commands you need.




回答3:


You can add something like this to your sudoers file:

username ALL=NOPASSWD: /path/to/script

This will allow that particular user to call sudo on that particular script without being prompted for a password.




回答4:


The best secure method is to use the crontab. ie Save all your commands in a database say, mysql table and create a cronjob to read these mysql entreis and execute via shell_exec(). Please read this link for more detailed information.

  * * * * * killProcess.php


来源:https://stackoverflow.com/questions/3166123/how-to-call-shell-script-from-php-that-requires-sudo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!