bash script does not work when called from PHP file? - php

I am trying to run a bash script from the web using php exec() method. The same bash script when ran from the terminal ./test.sh works fine executes all the command without any error. But when i try to run it from the command line it would absolutely not work. They both are in the same location. I have even give chmod 777 permission to that file.
Commnads like ls , pwd etc work but cf isn't working ?
test.sh
/usr/bin/cf login -a https://api.stage1.ng.bluemix.net -o jetmak#ca.blue.com -s dev -u jenk#ca.blue.com -p pass22
/usr/bin/cf api
/usr/bin/cf
executeshellfromphp.php
header('Content-Type: application/json');
$bluemixid = $_POST['bluemixid'];
$bluemixpwd = $_POST['bluemixpswd'];
$env = $_POST['env'];
$restart = $_POST['action'];
$result =shell_exec('sh /var/www/shellscriptphp/test.sh '.$env.' '.$restart.' '.$bluemixid.' '.$bluemixpwd.' ');
echo json_encode(array("result"=>$result));
exit();
Error:
FAILED
Config error: Error writing to manifest file:.cf/config.json
open .cf/config.json: no such file or directory

Related

Executing bash script from PHP on raspbian

I have a script that calls fswebcam to capture a jpg with my USB camera. I've made it executable with "chmod +x webcam.sh" :
File : /var/www/html/webcam.sh
#!/bin/bash
DATE=$(date + "%Y-%m-%d_%H%M")
fswebcam -r 640x480 /home/pi/webcam/$DATE.jpg
This is working fine in command line without sudo, so I've made a small PHP page :
File : /var/www/html/index.php
<?php
$output = shell_exec('sh /var/www/html/webcam.sh');
echo "<pre>$output</pre>";
?>
When I go to the webpage, I just get a blank page and no jpg is created in my webcam folder.
I got the following error :
Apache2 error log
So I've tried modifying my call in PHP, to :
<?php
$output = shell_exec('/usr/bin/sudo /bin/bash /var/www/html/webcam.sh');
echo "<pre>$output</pre>";
?>
I've also add the following to sudoers file
www-data ALL=NOPASSWD: /path/to/script
But I still get the error : apache2 log error
I've tried everything from this thread : How to run .sh script with php?
Do you have any idea ?
Thanks in advance,
Victor
First off:
Don't use sudo if you don't have a very good reason for it.
sh does not necessarily invoke bash.
sudo expects a password, but you didn't provide any hence the error.
I suggest trying with exec instead of shell_exec (there is a difference between the two):
<?php
exec('/var/www/html/webcam.sh', $output, $exitCode);
echo 'Exit code: '.$exitCode.' <hr />';
echo implode('<br />', $output);
Another source of your problem could be permission related:
The webserver usually runs as a different user.
Make sure the webserver can actually write to the output directory.

How do I allow www-data user to execute bash script with nginx

I an Ubuntu 16.04 machine running NGINX and PHP. I would like to enable the www-data user (via web browser) to be able to access a PHP page (php-test.php) that will execute either a bash script (script_test.sh) or execute Linux CLI commands using shell_exec or exec.
I have done the following.
Created my bash script file script_test.sh
#!/bin/bash
whoami
echo $USER
echo 'test'
exit
when I run this from CLI, using
./ script_test.sh
It does indeed work and I can see the info echoed out in the CLI.
I then pursued the goal of being able to allow the www-data user run this bash script through a PHP page running on this same machine from NGINX.
I created my php page (php_test.php) and it contains the following
<?php
chdir('/path/to/my/files/');
shell_exec('./script_test.sh'); // ATTEMPT RUN SCRIPT
shell_exec('/path/to/my/files/script_test.sh'); // ATTEMPT RUN SCRIPT
echo 'test 123'; // SIMPLE ECHO IN THE PHP PAGE
?>
I then ran the following to modify the sudoers file, giving www-data access to the bash script
sudo nano /etc/sudoers
to which I added the following line
www-data ALL=NOPASSWD: /path/to/my/files/script_test.sh
I then made sure the script was executable, for the sake of my testing, not worrying about security, I just set it to 777 with the following command
sudo chmod 777 script_test.sh
From there I opened a web browser and browsed to the localhost (NGINX) web server (php_test.php) and the only thing I see on the page is the 'test 123' that I echo from PHP... none of the bash script appears to have run at all. I tailed the NGINX error log and don't see any error at all.
Is there another log that could contain clues on this?
What else should I check here?
The result of shell_exec() is returned as string. To display it in your browser, simply add echo.
<?php
chdir('/path/to/my/files/');
echo shell_exec('./script_test.sh'); // ATTEMPT RUN SCRIPT
echo shell_exec('/path/to/my/files/script_test.sh'); // ATTEMPT RUN SCRIPT
echo 'test 123'; // SIMPLE ECHO IN THE PHP PAGE
?>
See the Return Values in the manual:
The output from the executed command or NULL if an error occurred or
the command produces no output.
Can you try to use passthru instead of shell_exec, and see the output anything?
Also try this, and see if it shows on the log file:
if(file_exists('/path/to/my/files/script_test.sh')) { die('File not found!'); }
shell_exec("nohup /path/to/my/files/script_test.sh > /path/to/my/files/output.log &");
Also, are you running PHP with the www-data user (check your fpm pool)?
Do you have any error on /var/log/syslog or /var/log/auth.log ?
Have you restarted the server after changing the sudo permissions?
What does su - www-data -c "whoami" and su - www-data -s /bin/bash -c "whoami" outputs?
Does su - www-data -s /bin/bash -c "/path/to/my/files/script_test.sh" output something?

Run linux command from web page

I am trying to run command from a web page (php) to my linux server. My php page look like this: $old_path = getcwd();
chdir('/var/www');
$output = shell_exec('./test.pl');
chdir($old_path);
test.pl is a simple test file that create a txt file.
If I run the command php /var/www/page.php everything works fine, but when I request the page in the browser nothing happen.
Thanks !
Make the owner of the file the apache/php user www-data:www-data
sudo chown www-data:www-data /var/www/test.pl
Give the group and others the right to execute it
chmod go+x /var/www/test.pl
Then put the absolut path into shell exec
$output = shell_exec('/var/www/test.pl');
var_dump($output);

directory is not creating while running bash shell script in php

i want to execute a bash shell script in php. The shell script used to create make a directory. But it is not creating while i am running the .php file in server.
The php code for above i have used-------
<html>
<?php
echo exec('./home/biswajit/lh.sh')
?>
thanx
</html>
And the code for corresponding lh.sh file is------
#!/bin/bash
cat <<EOF | /home/biswajit/matlab -nodesktop -nosplash -nodisplay /> /home/biswajit/matlab_result.out
mkdir('/home/biswajit/Done');
disp('directory created');
exit
EOF
Check with which user's permissions it's run. You could echo the output of "whoami" (bash) command to know with wich user is used to run the script.
If it's executed, for example, with the "www-data" user (ubuntu's [and maybe others] default httpd user), then it may not have the rights to create a directory in your user's home folder.
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('cat <<EOF | /home/biswajit/matlab -nodesktop -nosplash -nodisplay /> /home/biswajit/matlab_result.out');
$return2 = $shell->exeCmd('mkdir -p \'/home/biswajit/Done\'');
//the return will be a string containing the return of the command
echo $return1;
echo $return2;

What is linux equivalent of running a .bat file on windows from PHP using system()

I have a PHP script that runs a .bat file on my windows machine using
$result = system("cmd /C nameOfBatchFile.bat");
This sets some environmental variables and is used to call Amazon EC2 API from the command line.
How do I do the same from a Linux server? I have renamed my .bat file to a shell (.sh) and changed the script to use 'export' when setting env vars. I have tested by running the code from a putty terminal and it does what it should. So I know the commands in the script are good. How do I run this from PHP? I have tried running the same command as above with the new filename and I don't get any errors, or file not found etc but it doesn't appear to work.
Where do I start trying to solve this?
---------------------------------- UPDATE -------------------------------
Here is the PHP script that calls the shell file -
function startAmazonInstance() {
$IPaddress = "1.2.3.4"
$resultBatTemp = system("/cmd /C ec2/ec2_commands.sh");
$resultBat = (string)$resultBatTemp;
$instanceId = substr($resultBat, 9, 10);
$thefile = "ec2/allocate_address_template.txt";
// Open the text file with the text to make the new shell file file
$openedfileTemp = fopen($thefile, "r");
contents = fread($openedfileTemp, filesize($thefile));
$towrite = $contents . "ec2-associate-address -i " . $instanceId . " " . $IPaddress;
$thefileSave = "ec2/allocate_address.sh";
$openedfile = fopen($thefileSave, "w");
fwrite($openedfile, $towrite);
fclose($openedfile);
fclose($openedfileTemp);
system("cmd /C ec2/mediaplug_allocate_address_bytemark.sh");
}
And here is the .sh file - ec2_commands.sh
#!/bin/bash
export EC2_PRIVATE_KEY=$HOME/.ec2/privateKey.pem
export EC2_CERT=$HOME/.ec2/Certificate.pem
export EC2_HOME=$HOME/.ec2/ec2-api-tools-1.3-51254
export PATH=$PATH:$EC2_HOME/bin
export JAVA_HOME=$HOME/libs/java/jre1.6.0_20
ec2-run-instances -K $HOME/.ec2/privateKey.pem -C $HOME/.ec2/Certificate.pem ami-###### -f $HOME/.ec2/aws.properties
I have been able to run this file from the command line so I know that the commands work ok. When I had this working on windows there would be a delay as the instance started up and I could echo the results to the screen. Now there is no delay as if nothing is happening.
Put a hash-bang on the first line of your shell script.
#!/bin/bash
Then give it the executable flag.
$ chmod a+x yourshellscript
You can then call it from PHP with system.
$result = system("yourshellscript");
$result = system("/bin/sh /path/to/shellfile.sh");
Is script executable? If not, make it so:
$ chmod a+x script.sh # shell
system ("/path/to/script.sh"); // PHP
or launch it via interpreter:
system("sh /path/to/script.sh"); // PHP
Is interpreter specified in shell script (ie. #!/bin/sh line)?
have you tried shell_exec() ?

Categories