Execute program in shell script using php - php

I'm trying to automatise some Unity3D process to can call this from a PHP script.
I've already create an shell script that call some UNITY command line to create a project and for execute methods and if I use it in the terminal, works fine.
The problem is when I use it into a PHP script:
- I'm using shell_exec command to execute my script and all shell methods works (ls, mkdir, echo) but when I call to application nothing happend.
I was reading that is a permission problem into apache but after some hours I still without find a solution so.
I've mounted a server in my mac (Sierra) enabling apache and PHP 5 to test.
Regards,
Gabriel
EDIT 1
I add here my code
This is my shell_script that works fine if i execute it in a terminal.
#!/bin/bash
UNITY_EXEC=/Applications/Unity_5.6.1f1/Unity.app/Contents/MacOS/Unity
if [ -z "$2" ]; then echo "You must provide a path to the bundle assets and a path to the resulting bundle."; exit 1; fi
export UNITY_ASSET_BUNDLE_PATH=${2}
CREATION_TIME=`date +%s`
ASSET_BUNDLE_PROJECT_DIR=/tmp/AssetBundle-${CREATION_TIME}
echo "Creating temporary project.";
${UNITY_EXEC} -batchmode -quit -createProject ${ASSET_BUNDLE_PROJECT_DIR};
echo "Copying resources from source folder to assets folder.";
cd $1; cp -r . ${ASSET_BUNDLE_PROJECT_DIR}/Assets;
echo "Finding assets.";
cd ${ASSET_BUNDLE_PROJECT_DIR};
ASSETS_TO_BUNDLE=`find Assets -type f -not -name *.meta -not -name .DS_Store -not -name AssetsBundler.cs | sed 's/^.\///g' | sed 's/^/assetPathsList.Add("/g' | sed 's/$/");/g'`
mkdir ${ASSET_BUNDLE_PROJECT_DIR}/Assets/Editor/;
cat << EOT >> ${ASSET_BUNDLE_PROJECT_DIR}/Assets/Editor/AssetsBundler.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
public class AssetsBundler{
public static void Bundle(){
List<string> assetPathsList = new List<string>();
${ASSETS_TO_BUNDLE}
ArrayList assetList = new ArrayList();
foreach(string assetPath in assetPathsList)
{
UnityEngine.Object[] assets = AssetDatabase.LoadAllAssetsAtPath(assetPath);
foreach(UnityEngine.Object asset in assets)
{
assetList.Add(asset);
}
}
UnityEngine.Object[] allAssets = (UnityEngine.Object[]) assetList.ToArray(typeof(UnityEngine.Object));
BuildPipeline.BuildAssetBundle(allAssets[0], allAssets, "${UNITY_ASSET_BUNDLE_PATH}", BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.Android);
}
}
EOT
echo "Building the bundle.";
${UNITY_EXEC} -batchmode -quit -projectProject ${ASSET_BUNDLE_PROJECT_DIR} -executeMethod AssetsBundler.Bundle;
And this is my PHP_script
<?php
$old_path = getcwd();
chdir('./AssetBundleBuilder/');
$output = shell_exec('./AssetBundleBuilder ./Bundlify ./result.unity3d');
chdir($old_path);
echo $output;
?>
If i execute my PHP script from firefox, i receive as output all echo messages so thats tell me that the script is working. The thing is that the UNITY calls doesn't works.

I'll response my self.
Finally i got a solution using sockets. I've created a server socket in python to call the bash script in every connection and my client socket is in php that is the file that i call from a browser.
Thanks!
Gabriel

Related

PHP Bash Script calling another Bash script

I have a bash script that takes a parameter is called in PHP by shell_exec(script.sh parameter). Basically, my goal is to call a script that is owned by another user that is not apache.
The script.sh script is a file that contains the following (right now there are some error handling commands):
#/bin/bash
whoami>>whoami
echo $1 >> parameter
while read f; do
env>>envoutput
sudo -i -u archivescriptowner /path/to/archivescript.sh -command archive >> output
done < $1
In my /etc/sudoers file , I have the following:
apache ALL=(archivescriptowner) NOPASSWD: /bin/bash -c /path/to/archivescript.sh *
When I run this script as by running su -s /bin/bash apache and pass a parameter, it works.
When I run it via my button in php, archivescript.sh does not execute
The whoami file has apache written to it
The parameter file has the right file written to it
env shows the following
Term=xterm
LD_LIBRARY_PATH=/path/to/library
PATH=/sbin/:usr/sbin:/bin:/usr/bin
PWD=/var/www/html
LANG=C
SHLVL=4
=/bin/env
PWD is outputting right, that is where my script is right now, it will be moved in the future.
The output file when it is ran by the button click is blank.
I am at a loss as to why this is not working. Any insight would be helpful. Please let me know if I need to give any additional information.
I recently published a project that allows PHP to obtain and interact with a real Bash shell. 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('/path/to/archivescript.sh');
echo $return1; //return from your script

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;

SSH Command From PHP not working. Command runs fine from command line

I inherited this intranet app which unzips some requested spooled reports and dumps them into a Samba folder users have access to. Here's the PHP:
$command = "$unzip_program $path_spooled/$zip_file $filename -d $target_dir";
$ssh_command = "$ssh_syscommand -i /web/live/sshkey_nopass reportuser#$archive_server \"$command\"";
$sshpipe2 = popen( $ssh_command, 'r' );
So if I echo the SSH command being run it's:
/usr/bin/ssh -i /web/live/sshkey reportuser#192.168.1.21 "/usr/bin/unzip -c /reports/spooled/2012/jan.zip 01SU7C.RPT" |
/usr/bin/ssh -i /web/live/sshkey reportuser#192.168.1.2 "cat > /reports/spooled/01SU7C.RPT"
(I inserted a carriage return after the pipe for readability)
If I execute that command from the command line it works fine. If run from php it fails with no errors.
All I need is some help working out where to look. I figure it could be a missing ssh key, but the server does show a login from that user when the command is executed.
What am I missing? Where should I look? Is there something about unzip I don't know about? Do I need to set some sort of context from Apache?

PHP how to execute a command

I'm trying to use LibreOffice for converting a spreadsheet to another format, when I execute the command from the console it works fine but when I do it from PHP using exec() or system() it doesn't work.
It doesn't show any error or anything, it simply silently fails, if I try executing some simple command like "ls" it works just fine.
This is the command I'm using:
<?php
system("libreoffice --headless -convert-to ooxml '/home/www/path_to_app/file.xlsx' -outdir /home/www/path_to_app/");
I already tried changing the apache User and Group on /opt/lampp/etc/httpd.conf to the same logged in user I am.
I'm wondering if the problem is that the www folder is /home instead of inside my user and that causes permissions problems, but so far couldn't make it work.
Any help will be appreciated.
I solved this problem with the command below :
system('
export HOME=/tmp
libreoffice --headless --invisible --norestore --convert-to pdf --outdir /my/folder /my/file/calc.xls');
I solved this problem with the command below :
exec('libreoffice --headless --invisible --norestore --convert-to pdf --outdir /my/folder /my/file/calc.xls');
Just check rights, libreoffice uses user home folder, If you use default settings for Ubuntu then PHP runs oenter code heren www-data rights and it's home is /var/www/, but default this directory is owned by root.enter code here
In PHP - you can see rigths:
exec('whoami', $arr);
print_r($arr);
In console - You can see your HOME and give correct rights:
su wwww-data
echo $HOME
exit;
chown www-data:www-data /var/www -R
Notwithstanding your $PATH, which drew010 alluded to, I wouldn't do it this way.
LibreOffice is a pretty big program, has lots of code you don't know about, it generates and updates files in a directory in your $HOME, and is certainly not something you're going to be able to run more than one copy of at a time.
So instead of having LibreOffice launched by your web server, and subverting Apache's security by running it as a more privileged user than "www-data" or "nobody", you should make a handler.
First off, verify that you can run your libreoffice ... command line from a terminal. To be extra sure that you don't have any X11 dependencies, run unset DISPLAY (for bash) or unsetenv DISPLAY (for tcsh) in your xterm before you test your command line. Does it break? Fix that problem first. Does it work? Great, then proceed with a handler.
Your handler, in its simplest form, can be a script that loops forever, checking for "files to handle" in a spool directory, and if it finds them, converts them using libreoffice and puts the resultant file where it can be found by your web app.
#!/bin/sh
while sleep 10; do
if [ `ls /var/tmp/myspool/ | grep -c '\.xlsx$'` -gt 0 ]; then
ls /var/tmp/myspool/*.xlsx | while read file; do
/usr/local/bin/libreoffice --headless -convert-to ooxml "$file" yadda yadda
if [ $? = 0 ]; then
mv "$file" "/var/tmp/myspool/done/
fi
done
fi
done
If you don't want the overhead of something "polling" (checking the spool directory every 10 seconds), then you could have your PHP script add a line to a log that gets watched by your handler. For example:
<?php
// process form, save file to spool dir
syslog(LOG_NOTICE, "Saved: " . $filename);
?>
Make sure you've configured syslog to store these messages in, say, /var/log/filelog, then your handler can just tail the log.
#!/bin/sh
tail -F /var/log/filelog | while read line; do
filename="`echo \"$line\" | sed 's/.*Saved: //'`"
/usr/local/bin/libreoffice --headless -convert-to ooxml "$file" yadda yadda
# etc ... error handling and mv as in the other script
done
Get the idea?
I also faced same problem before.....
This solution seems worked for me...
function execInBackground($cmd) {
if (substr(php_uname(), 0, 7) == "Windows"){
pclose(popen("start /B ". $cmd, "r"));
}
else {
exec($cmd . " > /dev/null &");
}
}
$mainFile = "YOUR FILE";
$cmd2 = "export HOME=/tmp
libreoffice --headless --invisible --norestore --convert-to pdf " .
"'$mainFile'";
$saved = getenv("LD_LIBRARY_PATH"); // save old value
$newld = "/usr/lib"; // extra paths to add
if ($saved) {
putenv("LD_LIBRARY_PATH=" . $newld);
}
// set new value
//
// command is loaded using
// libs in the new path list
execInBackground($cmd2);
putenv("LD_LIBRARY_PATH=$saved"); // restore old value

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