简体   繁体   English

用PHP执行shell命令

[英]execute shell command with php

im trying to execute a bash script with a php/html button to wake my nas. 我试图用php/html按钮执行bash脚本来唤醒我的nas。

<form action="" method="POST">
    <input type="submit" value="Wake NAS" name="zero" />
</form>
<?php
  if (isset($_POST["zero"])){
    #echo "Hello World!";
    shell_exec("/var/www/html/wakenas.sh &");
  }?>

"Hello World" is printed when button is pressed. 按下按钮时,将打印“ Hello World”。 but code won't be executed. 但是代码不会被执行。 the wakenas.sh looks like this and works if i execute it over shell wakenas.sh看起来像这样,并且如果我在外壳上执行它,则可以正常工作

#!/bin/bash
etherwake -D "BC:5F:F4:09:E1:07"
echo "why!?!?!" > "/var/www/html/works.txt"
exit 1

wakenas.sh has all rights wakenas.sh所有权利

Maybe you guys know why it wont be executed. 也许你们知道为什么它不会被执行。

thanks in advance 提前致谢

From your dump: 从您的转储中:

etherwake: This program must be run as root.

when you execute wakenas.sh you probably are executing it as root. 当执行wakenas.sh时,您可能是以root用户身份执行它。 That's why it works. 这就是为什么它起作用。

Give the sudo permission (without password) to the user that your php server is running. 向您的php服务器正在运行的用户授予sudo权限(无密码)。

And change the wakenas.sh to: 并将wakenas.sh更改为:

#!/bin/bash
sudo etherwake -D "BC:5F:F4:09:E1:07"
echo "why!?!?!" > "/var/www/html/works.txt"
exit 1

I recently published a project that allows PHP to obtain and interact with a real Bash shell (as root if requested), it solves the limitations of exec() and shell_exec(). 我最近发布了一个项目,该项目允许PHP获取和与真实的Bash shell(如果需要,请作为根)进行交互,它解决了exec()和shell_exec()的局限性。 Get it here: https://github.com/merlinthemagic/MTS 在这里获取它: https : //github.com/merlinthemagic/MTS

After downloading you would simply use the following code: 下载后,您只需使用以下代码:

$shell    = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$return1  = $shell->exeCmd("etherwake -D \"BC:5F:F4:09:E1:07\"");
//the return will be a string containing the return of the command
echo $return1;

The easy and secure way of executing your script is to put in sudoers. 执行脚本的简单而安全的方法是放入sudoers。 Assuming your Linux distribution is Debian base and user of who run the web server is www-data , then you can create a file eg /etc/sudoers.d/wakeup_ether 假设您的Linux发行版基于Debian,并且运行Web服务器的用户是www-data ,那么您可以创建一个文件,例如/etc/sudoers.d/wakeup_ether

Cmnd_Alias WAKE_UP_CMD = /var/www/html/wakenas.sh
www-data ALL=NOPASSWD: WAKE_UP_CMD

Modify your script to prefix the command with sudo . 修改脚本,以在命令前添加sudo

shell_exec("sudo /var/www/html/wakenas.sh &");

Reference: https://help.ubuntu.com/community/RootSudo 参考: https : //help.ubuntu.com/community/RootSudo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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