sudo_exec returns nothing - php

I try to ping www.google.de with shell_exec and store the result into a variable but i get no result back from shell_exec.
<?php
$ping = 'sudo ping -c 4 ';
$url = 'www.google.de';
$command = $ping . $url;
$ping_result = shell_exec($command);
$datei = fopen("/var/www/myProject/result_ping","w") or die ("Could not open file!");
sleep(10);
if ($datei == false)
{
$ping_result = "Cannot open file!";
}
else
{
fwrite ($datei , $ping_result);
fclose ($datei);
}
echo $command; //Output: sudo ping -c 4 www.google.de
echo $ping_result; //Output: nothing
?>
The file result_ping has all rights (chmod 777).
Maybe the webserver is not allowed to execute ping?

Add 2>&1 to your command to ensure you're not getting an error message that shell_exec would filter off:
$command = $ping . $url . ' 2>&1';
shell_exec will return NULL in case of error. With that modification you redirect any error message to normal output, thus forcing shell_exec show every message you would normally get on a console session.

Related

PHP not executing shell script and overloading apache

I want to execute my book generator script with php.
I tried to run my script on my linux terminal and all worked out fine.
sudo /home/repoadmin/apple/arduino.raamatu.generaator.sh
I used some execute function from stackoverflow to see what it echos during execute(also tried regular exec() and shell_exec()):
function liveExecuteCommand($cmd)
{
while (# ob_end_flush()); // end all output buffers if any
$proc = popen("$cmd 2>&1 ; echo Exit status : $?", 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
$live_output = fread($proc, 4096);
$complete_output = $complete_output . $live_output;
echo "$live_output";
# flush();
}
pclose($proc);
// get exit status
preg_match('/[0-9]+$/', $complete_output, $matches);
// return exit status and intended output
return array (
'exit_status' => intval($matches[0]),
'output' => str_replace("Exit status : " . $matches[0], '', $complete_output)
);
}
define('__FILEDIR__','/home/repoadmin/apple');
chdir(__FILEDIR__);
readdir(__FILEDIR__);
liveExecuteCommand("sudo /home/repoadmin/apple/arduino.raamatu.generaator.sh");
closedir(__FILEDIR__);
I added www-data ALL=NOPASSWD:/home/repoadmin/apple/arduino.raamatu.generaator.sh to /etc/sudoer for executing with sudo.
My apache2 server freezes when I'm executing this php. When I restart my apache2, the output what I get is this:
/home/repoadmin/apple/arduino/arduino_raamat.pdf Could not open input file: /home/www/xxx/xxx/bookcreator.php?lang=et&toc=arduinotoc&book=book --2017-07-14 15:34:11-- http://xxx.xxx.xx/bookcreator.php Resolving xxx.xxx.xx (xxx.xxx.xx)... 195.xxx.xxx.xxx Connecting to xxx.xxx.xx (xxx.xxx.xx)|195.xxx.xxx.xxx|:80... connected. HTTP request sent, awaiting response... 200 OK Length: unspecified [text/html] Saving to: '/home/repoadmin/apple/bookcreator_output.html' 0K .
What could be the problem and how can I fix it?

Executing bash with PHP

I want to execute bash command with script. If I echo the command, I get the proper response. But if I execute it from browser, it does not work. If I echo the command ls, it is executed and shown. I have granted all permissions. If I write command in terminal it works.
<?php
$banlista = $_POST['banlista'];
$ip = $_POST['ip'];
$command = "fail2ban-client set $banlista banip $ip";
$sporocilo = shell_exec("$command");
?>
It's better to run the command within the php code. You can get a response
from the actual command and verify that it worked.
If you have your code this way
<?php
$banlista = $_POST['banlista'];
$ip = $_POST['ip'];
$command = "fail2ban-client set $banlista banip $ip";
$sporocilo = shell_exec("$command");
?>
You can try to add this:
<?php
exec("sudo user /usr/bin/fail2ban-client set $banlista banip $ip", $output, $return);
echo "Failtoban client returned $return, and output:\n";
var_dump($output);
?>
You're probably missing a sudo and a user who has the right to run the
command from the browser.

Output stream on powershell for SSH calls

My PHP script (in Linux) is not printing my values on screen, however it prints a Warning message.
e.g.
This is my php code:
$stream = ssh2_exec($connection, 'powershell "c:\remoteScript.ps1" -$NotificationID "5359f76f888ddf35b889dedf"');
$string = stream_get_contents($stream);
echo "Powershell output: ". $string;
This is my powershell code:
Write-Warning "This is a test"
And this is what PHP is writing:
Powershell output: WARNING: You should update your PowerShell to
PowerShell 2.0 version.
QUESTION: How can I catch the the stream returned by Powershell?
SOLUTION: we need to tell ssh2_exec whether to wait/block until the remote process finishes search for "block" on this page to see an example.
$stream = ssh2_exec($connection, 'powershell \'C:\scripts\remoteVeeamClientSummary.ps1\' -Client \''. $Client. '\' -NotificationID \''. $NotificationID. '\'');
stream_set_blocking($stream, true);
return stream_get_contents($stream);
and powershell:
Write-Output $result

Error Reporting? Import .sql file from PHP and show errors

I am building a way of importing .SQL files into a MySQL database from PHP. This is used for executing batches of queries. The issue I am having is error reporting.
$command = "mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file";
exec($command, $output);
This is essentially how I am importing my .sql file into my database. The issue is that I have no way of knowing if any errors occurred within the PHP script executing this command. Successful imports are entirely indistinguishable from a failure.
I have tried:
Using PHP's sql error reporting functions.
Adding the verbose argument to the command and examining the output. It simply returns the contents of the .sql file and that is all.
Setting errors to a user variable within the .sql file and querying it from the PHP script.
I hope I am not forced to write the errors into a temporary table. Is there a better way?
UPDATE:
If possible, it would be very preferable if I could determine WHAT errors occurred, not simply IF one occurred.
$command = "mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname"
. " < $file 2>&1";
exec($command, $output);
The error message you're looking for is probably printed to stderr rather than stdout. 2>&1 causes stderr to be included in stdout, and as a result, also included in $output.
Even better, use proc_open instead of exec, which gives you far more control over the process, including separate stdout and stderr pipes.
Try using shell_exec
$output = shell_exec( "mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file" );
// parse $output here for errors
From the manual:
shell_exec — Execute command via shell and return the complete output as a string
Note:
This function is disabled when PHP is running in safe mode.
EDIT: Full solution:
what you need to do is grab STDERR and discard STDOUT. Do this by adding '2>&1 1> /dev/null' to the end of your command.
$output = shell_exec( "mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file 2>&1 1> /dev/null" );
$lines = explode( PHP_EOL, $output );
$errors = array();
foreach( $lines as $line )
{
if ( strtolower( substr( $line, 0, 5 ) ) == 'error' )
{
$errors[] = $line;
}
}
if ( count( $errors ) )
{
echo PHP_EOL . 'Errors occurred during import.';
echo implode( PHP_EOL, $errors );
}
else
{
echo 'No Errors' . PHP_EOL;
}
When issuing a exec, the shell will return a 0 on succes, or a number indicating a failure.
$result = exec( $command, $output );
should do the trick. Check result and handle appropiate.
You have done everything but look at the PHP manual! There is an additional parameter for the exec to return a result
http://php.net/manual/en/function.exec.php
"If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable."
exec($command,$output,$result);
if ($result === 0) {
// success
} else {
// failure
}

Starting a bash script from a php script

I'm trying to run a bash script using shell_exec but It doesnt seem to work. (Nothing seems to happen) I'm using nginx and the latest php5-cgi. Heres what the php file looks like:
<?php
$startserver = "./startserver.sh";
$startserver = shell_exec($startserver);
$getprocess = "pidof hlds_amd";
$pid = shell_exec($getprocess);
$fh = fopen('closeserver.sh', 'w');
$command = "kill -9 $pid";
fwrite($fh, $command);
fclose($fh);
$string = "at -f closeserver.sh now + 1 hour";
$closer = shell_exec($string);
?>
and this is what the bash script looks like:
#!/bin/bash
cd /home/kraffs/srcds
./hlds_run -game cstrike -autoupdate +maxplayers 12 +map de_dust2 > hlds.log 2>&1 &
Theres no errors in the phpscript and the file gets created just fine but $startserver doesnt seem to get executed and $pid is empty. Did I miss something in the php file or do I need to change permissions for an user? Thanks for your help.
replace shell_exec, with below function and try again
<?php
function runcmd($EXEC_CMD)
$handle = popen ($EXEC_CMD, 'r');
$output = "";
if ($handle) {
while(! feof ($handle)) {
$read = fgets ($handle);
$output .= $read;
}
pclose($handle);
}
return $output;
}
?>

Categories