Run bash script in response to HTTP POST - php

I have been using the following PHP script to trigger a bash script on a server:
<?php
$output = shell_exec('cat update.sh | ssh -l some_user -i key foo.bar.com');
echo "<pre>$output</pre>";
?>
Due to issues beyond my control, we've changed servers, and I cannot run PHP (don't ask). Is there another language I can use here that will accomplish this task? Something I can target with an HTTP POST, obviously. Thanks.

You could go old-school cgi-bin and run the bash script directly:
#!/bin/bash
x=`cat update.sh | ssh -l some_user -i key foo.bar.com`
echo <<EOL
Content-type: text/html
<pre>$x</pre>
EOL

You could run a bash script directly with cgi.
#!/bin/bash
OUTPUT=`cat update.sh | ssh -l some_user -i key foo.bar.com`
# You must add following two lines before
# outputting data to the web browser from shell
# script
echo "Content-type: text/html"
echo ""
echo "<html><head><title>Demo</title></head><body>"
echo "$OUTPUT <br>"
echo "</body></html>"
Some code from here

It depends on server configuration. Task is very simple, so you can do it in every (I guess) technology your provider provides ;)
If you have access to perl:
#!/usr/bin/env perl
++$|;
print '<pre>';
system ('your command 2>&1');
print '</pre>';
Python and many others are similar.

Related

Incorrect Webpage Output for PHP exec running bash script for audtool (part of Audacious)

On a local linux server (Rapsberry Pi debian stretch with desktop), I am working on sending "audtool" commands to a running Audacious media player using php, exec and bash scripts. Audacious is autostarted when the server starts up with user "pi". I have apache2 and php set up and working on the server, and I can ssh to the server and run all the commands from the cli. I believe I have resolved the issues with running audtool (dbus and setting the right environment variables) and running the php on the command line works successfully. However when running the php on a webpage I get back a long string of information about apache2
I have spent several hours (getting on for a whole day) researching this on the web in order to get to this stage, so close I can almost touch it, but stuck on this last element. The example is to display the current song from a running instance of Audacious. Audtool requires a running dbus (looks for a display). Using exec or shell_exec I have no problems running bash commands such as whoami or ls.
The php page (cursong.php):
<?php
echo exec('/var/www/html/cursong.sh');
?>
The bash script (cursong.sh):
#!/bin/bash
##call current song
pid=`pidof audacious`
user=`ps -p $pid -o user=`
export `strings /proc/$pid/environ | grep DBUS_SESSION_BUS_ADDRESS`
sudo -E -su $user /usr/bin/audtool --current-song
(from here: https://redmine.audacious-media-player.org/boards/1/topics/1058?r=1059)
Output from command line:
php -f cursong.php
Artist - Song Title (for example - so this works)
Output on webpage:
declare -x APACHE_LOCK_DIR="/var/lock/apache2" declare -x
APACHE_LOG_DIR="/var/log/apache2" declare -x
APACHE_PID_FILE="/var/run/apache2/apache2.pid" declare -x
APACHE_RUN_DIR="/var/run/apache2" declare -x APACHE_RUN_GROUP="www-
data" declare -x APACHE_RUN_USER="www-data" declare -x
INVOCATION_ID="4ce76136ca8842bd9108d6b1b9a5b9ed" declare -x
JOURNAL_STREAM="8:23896" declare -x LANG="C" declare -x OLDPWD
declare -x
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
declare -x PWD="/var/www/html" declare -x SHLVL="1"
I have set www-data, the apache2 user with the following in
/etc/sudoers:
www-data ALL=NOPASSWD: ALL
and /var/www/html is rwx for anyone
Obviously, I am expecting to see "Artist - Song Title" on the webpage, but instead I get back all the apache2 info. What am i missing, or where have I gone wrong?
I hate answering my own question, makes it look like I wasn't trying hard enough! After a further five hours or so of searching around and attempting fixes, I happened upon this post on SO:
Running command-line application from PHP as specific user
which suggested putting a "sudo -u user" in the exec of the php file. I tried this with the "pi" user and it still didn't work, then I simply tried it with "sudo" and hey presto!!
The php file now looks like this:
<?php
echo shell_exec('sudo /var/www/html/cursong.sh 2>&1');
?>
Now to do some testing on how it works with the other audtool commands that don't ask for a response but require action from audacious, and to see how I can reduce scripting php files by passing a parameter to the bash script!
Just for completeness, the php and bash scripts for both a request and an action, using a parameter fed to the php url and then on to the bash script:
PHP File with Parameter
<?php
$request = $_GET["request"];
echo shell_exec("sudo /var/www/html/cursong.sh \"${request}\" 2>&1");
?>
url example:
http://192.168.1.92/cursong.php?request="--playlist-shuffle-status"
Bash Script with parameter
#!/bin/bash
##call request
pid=`pidof audacious`
user=`ps -p $pid -o user=`
export `strings /proc/$pid/environ | grep DBUS_SESSION_BUS_ADDRESS`
sudo -E -su $user /usr/bin/audtool $1
PHP file for an action
<?php
$action = $_GET["action"];
shell_exec('sudo /var/www/html/playsong.sh \"${request}\" ');
?>
url example:
http://192.168.1.92/cursong.php?action="--playback-play"
Bash script for an action
#!/bin/bash
##call action
pid=`pidof audacious`
user=`ps -p $pid -o user=`
export `strings /proc/$pid/environ | grep DBUS_SESSION_BUS_ADDRESS`
sudo -E -su $user /usr/bin/audtool $1

launching php script running on server (and opening sockets) from a php page

I'd need you precious help on a matter I am spending hours on.
Scope: Apache2 and PHP running on a raspberry pi;
Premise: my little knowledge of Linux environment!
The objective: launching a long-run php script, that opens sockets, from another php script running as webpage. In other terms, the application is a chat and I need to start the php server script form a web page, for my convenience.
The issue: if I run it from the the console, logged as "pi", with the following command
php -q /var/www/chatSocket.php > /var/www/tmp/socketProcessOutput.txt 2>&1 & echo $!
it works like a charm, but if it try to do so from a script, with the following (don't mind the concatenated strings and assignment of output to variables - it made no difference removing them):
$result .= "Result of pkill (killed process): " .shell_exec('sudo pkill -f SongWebSocket.php') ."\n";
$result .= "Launching new process: id returned:". shell_exec('php -q /var/www/chatSocket.php > /var/www/tmp/socketProcessOutput.txt 2>&1 & echo $!') ."\n";
$result .= "Checking running SongWebSocket.php process:" ."\n";
$result .= shell_exec('ps -A aux| grep -e SongWebSocket.php -e USER') ."\n";
.. it does not work (it seems like it launch the script but the sockets ar not open).
Any clue why this happens?
Also, and this can be for my little knowledge of Linux, why i get a dioffrent aoutput from the command
ps aux| grep -e SongWebSocket.php -e USER
if I launch it from the shell, as user pi, or from the sript, as www-data user.
I Look forward for your help. Thanks in advance!
Marco.
www-data user doesn't have the permisson I guess. why not add "sudo" for every shell_exec line? (sudo starts the programm with root permission). it's not pretty and not secure but it might work on you local home-network. sudo php ... sudo ps -A aux etc. In addition you should make sure that the php safe_mode is off. you can see that by adding phpinfo(); to you php code

Calling shell script from PHP is not working as expected

I am trying to open remote machine browser from my machine. I have setup password less connection ( considering the fact that both systems are in same n/w and are trusted).
I am able to run below script to launch browser, which takes 3 arguments
a). userName
b). ip address of remote machine
c). url to open in firefox
If i run this script in my bash shell, i am able to open the browser without any issues. But if i call this inside PHP, i am not able to launch the browser on remote machine...it shows all debug prints but fails open browser. Any pointers are greatly helpful. Below is my shell script to open browser on remote machine.
#!/bin/bash
if test $# != 3;
then
echo "
$0
This command line script is used to launch, browser remotely. You need to pass 3 arguments to this script.
YOU NEED TO PASS 3 ARGUMEMTS TO THIS SCRIPT,
For example , \$> sh $0 \"<userNameofRemoteSystem>\" \"<remoteSystemIP>\" \"<webPageAddress>\"
\$> sh $0 \"Uname\" \"172.17.64.94\" \"mail.google.com\" \n";
exit 1
fi
echo "<br><br>\nRECEIVED PARAMETERS,\n\tuserName\t-> |$1|\n\tipAddress\t-> |$2|\n\twebURL\t\t-> |$3|\n\n<br>";
echo "<br>Checking if Connection to |$2| WITH USERNAME |$1| is password less???<br><br>";
sleep 2
echo "<br>grep -wc $1 /home/user/.ssh/authorized_keys<br>";
count=`grep -wc $1 /home/user/.ssh/authorized_keys`;
echo "<br>got process count=|$count|<br>"
sleep 2
if [ "$count" != 1 ];
then
echo "
Looks like password less connection to |$2| is not configured with this server for username |$1|..
Please congfigure the same and run this script again...\n";
fi
echo "SUCCESSFULLY CONNECTED, LAUNCHING BROWSER ON |$2| WITH |$3|\n";
ssh $1#$2 "nohup sh openBrowser.sh $3" &
PID=$$;
echo "PID IS |$PID|\n";
sleep 2;
echo "<br>PROCESS OUTPUT LOOKS LIKE THIS";
ps aux | grep $PID | grep -v grep
echo "<br>";
echo "after sleep";
kill -9 $PID && echo "after kill pid=$PID, passed ssh $1#$2 \"nohup sh openBrowser.sh $3\" &";
Below is the php script i am using to call the shell script.
<?php
$c_url=$_POST['url'];
$c_name=$_POST['uname'];
$c_ip=$_POST['ipaddress'];
$output = system("/bin/sh /home/user/launchBrowser_remote.sh $uName $ipADDR $c_url");
echo "$output";
?>
Looks like i am getting wrong PID inside shell script and its killing the caller script rather than launching the ssh to remote ..... BTW i have tried both exec and shell_exec but no luck.
Any pointer are greatly helpful
Thanks
Make sure that the user that is running the php file (web server user if being called in that context) is set up for password-less authentication as well.

php shell_exec echo

I'm working on interfacing a microcontroller with a lamp server. I am trying to run the command echo -e -n "data \r" > /dev/ttyUSB0 using shell_exec in php but with no results. It works just fine from the command line. Doing a little experimenting, I discovered that echo -e -n "1 \r" actually echoes -e -n 1. Is there a reason it won't take the -e or -n options?
Here's my code:
<?php
shell_exec('echo -e -n "1 \r" > /dev/ttyUSB0');
?>
Instead of using shell_exec and echo, why not use PHP's filesystem functions?
file_put_contents('/dev/ttyUSB0', "1 \r");
There are some other functions too, try this function maybe you get your answer.
exec(command, $output);
This function takes a command and assigns to $output an array where each element is a line of the generated output.
I ran into similar problem, calling from php
php > echo shell_exec("echo -e aaa\tbbb");
-e aaa bbb
note, that output contains "-e", while I have expected that 'echo' command will interpret -e as flag and would not send it to output.
After doing some investigation I came to following conclusion:
when exec or shell_exec are called from php - new shell interpreter is launched.
php launches "sh".
When I was running on CentOS sh was a symlink to bash, and exec("echo ...") worked as I would have expected.
Now I am running Ubuntu. sh is a symlink to dash, not bash!
And final root cause - builtin echo command in dash does not have/understand '-e' flag, so it just forwards it to output
This is an old question but it goes what worked for me in case someone else comes across with this as well.
Yesterday night I've messing around and struggling with this myself. For this to work, the command you need to use should start by calling the echo bin directly /bin/echo... instead of only echo.
Also don't forget to use single quote /bin/echo... instead of double quote to avoid PHP null byte detection error (this part you did correctly).
I had a similar problem running with -e, I was trying to change the password from a php
running this didnt work
exec("echo -e \"$pass\\n$pass\" | passwd $user");
It said passwords dont match. Checking the echo i saw that -e was includes as a part of the echoing so i changed it to
exec("echo \"$pass\\n$pass\" | passwd $user");
And then it worked.

How to check if a php script is still running

I have a PHP script that listens on a queue. Theoretically, it's never supposed to die. Is there something to check if it's still running? Something like Ruby's God ( http://god.rubyforge.org/ ) for PHP?
God is language agnostic but it would be nice to have a solution that works on windows as well.
I had the same issue - wanting to check if a script is running. So I came up with this and I run it as a cron job. It grabs the running processes as an array and cycles though each line and checks for the file name. Seems to work fine. Replace #user# with your script user.
exec("ps -U #user# -u #user# u", $output, $result);
foreach ($output AS $line) if(strpos($line, "test.php")) echo "found";
In linux run ps as follows:
ps -C php -f
You could then do in a php script:
$output = shell_exec('ps -C php -f');
if (strpos($output, "php my_script.php")===false) {
shell_exec('php my_script.php > /dev/null 2>&1 &');
}
The above code lists all php processes running in full, then checks to see if "my_script.php" is in the list of running processes, if not it runs the process and does not wait for the process to terminate to carry on doing what it was doing.
Just append a second command after the script. When/if it stops, the second command is invoked. Eg.:
php daemon.php 2>&1 | mail -s "Daemon stopped" you#example.org
Edit:
Technically, this invokes the mailer right away, but only completes the command when the php script ends. Doing this captures the output of the php-script and includes in the mail body, which can be useful for debugging what caused the script to halt.
Simple bash script
#!/bin/bash
while [true]; do
if ! pidof -x script.php;
then
php script.php &
fi
done
Not for windows, but...
I've got a couple of long-running PHP scripts, that have a shell script wrapping it. You can optionally return a value from the script that will be checked in the shell-script to exit, restart immediately, or sleep for a few seconds -and then restart.
Here's a simple one that just keeps running the PHP script till it's manually stopped.
#!/bin/bash
clear
date
php -f cli-SCRIPT.php
echo "wait a little while ..."; sleep 10
exec $0
The "exec $0" restarts the script, without creating a sub-process that will have to unravel later (and take up resources in the meantime). This bash script wraps a mail-sender, so it's not a problem if it exits and pauses for a moment.
Here is what I did to combat a similar issue. This helps in the event anyone else has a parameterized php script that you want cron to execute frequently, but only want one execution to run at any time. Add this to the top of your php script, or create a common method.
$runningScripts = shell_exec('ps -ef |grep '.strtolower($parameter).' |grep '.dirname(__FILE__).' |grep '.basename(__FILE__).' |grep -v grep |wc -l');
if($runningScripts > 1){
die();
}
You can write in your crontab something like this:
0 3 * * * /usr/bin/php -f /home/test/test.php my_special_cron
Your test.php file should look like this:
<?php
php_sapi_name() == 'cli' || exit;
if($argv[1]) {
substr_count(shell_exec('ps -ax'), $argv[1]) < 3 || exit;
}
// your code here
That way you will have only one active instace of the cron job with my-special-cron as process key. So you can add more jobs within the same php file.
test.php system_send_emails sendEmails
test.php system_create_orders orderExport
Inspired from Justin Levene's answer and improved it as ps -C doesn't work in Mac, which I need in my case. So you can use this in a php script (maybe just before you need daemon alive), tested in both Mac OS X 10.11.4 & Ubuntu 14.04:
$daemonPath = "FULL_PATH_TO_DAEMON";
$runningPhpProcessesOfDaemon = (int) shell_exec("ps aux | grep -c '[p]hp ".$daemonPath."'");
if ($runningPhpProcessesOfDaemon === 0) {
shell_exec('php ' . $daemonPath . ' > /dev/null 2>&1 &');
}
Small but useful detail: Why grep -c '[p]hp ...' instead of grep -c 'php ...'?
Because while counting processes grep -c 'php ...' will be counted as a process that fits in our pattern. So using a regex for first letter of php makes our command different from pattern we search.
One possible solution is to have it listen on a port using the socket functions. You can check that the socket is still listening with a simple script. Even a monitoring service like pingdom could monitor its status. If it dies, the socket is no longer listening.
Plenty of solutions.. Good luck.
If you have your hands on the script, you can just ask him to set a time value every X times in db, and then let a cron job check if that value is up to date.
troelskn wrote:
Just append a second command after the script. When/if it stops, the second command is invoked. Eg.:
php daemon.php | mail -s "Daemon stopped" you#example.org
This will call mail each time a line is printed in daemon.php (which should be never, but still.)
Instead, use the double ampersand operator to separate the commands, i.e.
php daemon.php & mail -s "Daemon stopped" you#example.org
If you're having trouble checking for the PHP script directly, you can make a trivial wrapper and check for that. I'm not sufficiently familiar with Windows scripting to put how it's done here, but in Bash, it'd look like...
wrapper_for_test_php.sh
#!/bin/bash
php test.php
Then you'd just check for the wrapper like you'd check for any other bash script: pidof -x wrapper_for_test_php.sh
I have used cmder for windows and based on this script I came up with this one that I managed to deploy on linux later.
#!/bin/bash
clear
date
while true
do
php -f processEmails.php
echo "wait a little while for 5 secobds...";
sleep 5
done

Categories