2

I'm trying to execute a simple shell command and print the result on a web page but the results are empty. Below is one bit of code I found but nothing has worked thus far.

 <?php
            $server = "myserver";
            $username = "myadmin";
            $command = "ps";
            $str = "ssh " .$username. "@" .$server. " " .$command;

            exec($str, $output);

            echo '<pre>';
            print_r($output);
            echo '</pre>';
    ?>
Charles
  • 50,943
  • 13
  • 104
  • 142
tomtomssi
  • 1,017
  • 5
  • 20
  • 33

3 Answers3

6

Try phpseclib, that'll work.

<?php
    include('Net/SSH2.php');

    $server = "myserver";
    $username = "myadmin";
    $password = "mypass";
    $command = "ps";

    $ssh = new Net_SSH2($server);
    if (!$ssh->login($username, $password)) {
        exit('Login Failed');
    }

    echo $ssh->exec($command);
?>
ciruvan
  • 5,143
  • 1
  • 26
  • 32
0

You're missing the -p option before the port number:

$str = "ssh -p $port $username@$server $command";
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Using a more object oriented solution, you can install phpseclib version 2 with:

composer require phpseclib/phpseclib

And then just create your ssh object:

$ssh = new SSH2('yourhost');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

In this exemple i have used a connection through username and password but you can also connect via ssh-keys. If the connection is successful you can execute the method exec to execute you command on the server.

Community
  • 1
  • 1