简体   繁体   中英

execute shell command with php

im trying to execute a bash script with a php/html button to wake my 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. but code won't be executed. the wakenas.sh looks like this and works if i execute it over shell

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

wakenas.sh has all rights

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. That's why it works.

Give the sudo permission (without password) to the user that your php server is running.

And change the wakenas.sh to:

#!/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(). Get it here: 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. 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

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 .

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

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

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