5

So I have question which in my head should seem very simple to solve. I want to ssh to a server, which I have done a ton of times, and then make a shell execute which I have done a ton of times as well, but it is not working.

The code i am using

<?php
            $ip = '1.2.3.4';
            $cmd = "ssh user@".$ip;
            $result = shell_exec($cmd." 'sudo /bin/systemctl stop wildfly.service'");
            echo "<pre>output: $result</pre>";
            echo "<div class='alert alert-success'><strong>SUCCESS</strong><br>Wildfly node has now restarted</div>"; 
?>

Running the command directly from the terminal

ssh user@1.2.3.4 sudo /bin/systemctl stop wildfly.service

It works, but running it within php gives me nothing, and it not doing anything.

Can someone maybe guide me to what I am doing wrong with my shell_exec?

Thanks in advance!

pkj
  • 109
  • 1
  • 9

3 Answers3

-1
function execPrint($command) {
    try {
        $result = array();
        exec($command.' 2>&1', $result);
        foreach ($result as $line) {
            print($line .  "\n");
        }
        echo '------------------------' . "\n" . "\n";
    } catch (\Exception $e) {
        print($e);
    }
    http_response_code(200);
}

i made this function to get result

  1. add 2>&1 in last of the CMD
  2. use print with every line
  3. use try and catch to catch any error
A. El-zahaby
  • 1,130
  • 11
  • 32
  • Hi, well the thing is that this will be working fine, but my code up here will not work if it is associated with a button which are clicked on a page. I can put anything in the button and it will work, but if I put in this code I made it will not work. If I put it in a seperate file and run it from command line it works fine :S – pkj Mar 16 '19 at 15:38
-1

The user attempting to execute those shell commands from php is likely _www and not you. Try this code in your php to gain insight:

$shellscript = 'whoami';
$sr = shell_exec($shellscript);
echo '['.$sr.']';
jwbaumann
  • 19
  • 3
-1

Make sure the shell_exec function is not disabled. It usually is disabled by default in CPanel accounts PHP.ini and PHP-FPM .ini files.

You can check it using this validation

if (is_callable('shell_exec') && (false === stripos(ini_get('disable_functions'), 'shell_exec'))) {
    echo "shell_exec enabled";
} else {
    echo "shell_exec disabled";
}

It's the most common reason i've found for shell_exec to return always empty

You can also execute a quick command for testing purpouses

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

echo "Command: shell_exec('ls -lart')";
try {
    $output = shell_exec('ls -lart');
    echo "<pre>$output</pre>";
} catch (Exception $e) {
    echo $e->getMessage();
}