How to call shell script from php that requires SU

2019-01-01 13:09发布

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?

3条回答
若你有天会懂
2楼-- · 2019-01-01 13:55

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
查看更多
初与友歌
3楼-- · 2019-01-01 14:01

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.

查看更多
几人难应
4楼-- · 2019-01-01 14:09

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.

查看更多
登录 后发表回答