简体   繁体   中英

Using PHP shell_exec() to execute BASH script, can't write files

I'm using PHP to write an API to pass JSON parameters to a BASH script via POST. Here's a distilled version of what I'm doing:

<?php

$params = json_decode(file_get_contents('php://input'), true);

$cmd = "/bin/bash /path/to/myscript " . $params["value1"] . " " . $params["value2"] . " " . $params["value3"];
$output = "Command: " . $cmd . "\n\nResponse: " . shell_exec($cmd);

print($output);

?>

'myscript' is a simple test script with the following:

#!/bin/bash

echo -e "Executing script...your parameters are: [$1] [$2] [$3]\n"
echo -e "test" > /tmp/test.txt

Executing the script works and I get the first echo back showing the parameters were successfully passed. However trying to do anything within the script which writes to the filesystem (the second echo) does not happen. It is as if permissions are a problem, but I have made sure to write into directories where the 'apache' user has full permissions. I have also tried adding apache and my script command to sudoers and running via sudo passwordless, no luck. I have verified that paths are explicit and correct, users are correct, etc via adding the appropriate debug commands into both my php and bash scripts as suggested by the million other questions already posted. The script obviously works fine if I run it from the command line. It also works (and can write to the filesystem) if I 'sudo -u apache' to run the script, so I know permissions aren't a problem. I am stuck. Any ideas?

Edit with more info: I have also tried disabling SELinux, verified owners/permissions, tried writing to other directories with 777 permissions, and executed the script from the command line (outside PHP) with the apache user, all with no issues. It is only when performing from within shell_exec that I cannot write anything to the filesystem.

If it helps, I am on Centos7.

The culprit ended up being SELinux after all. After disabling I could write to specific directories, but still not others. Not sure why but even with SELinux disabled I can't write to /tmp when executing the script via shell_exec although I can when executing via cmd line. However shell_exec can write to my httpd root directories no problem.

Check your php.ini to see if open_basedir is set. This would restrict your php scripts from writing outside of that directory/sub directories.

I had the same problem when I enabled it and was unable to write to /tmp

grep open_basedir /etc/php/7.0/apache2/php.ini # Ubuntu

http://php.net/manual/en/ini.core.php#ini.open-basedir

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