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>';
    ?>
5
  • Is the ssh command working by itself, meaning did you try it command line first? Commented Aug 22, 2013 at 6:58
  • exec($str, $output, $return);. Check the error code too, var_dump(array($output, $return)); Commented Aug 22, 2013 at 7:02
  • also echo $str; get the string and try to run manually in shell. Commented Aug 22, 2013 at 7:03
  • @bjackfly Yes, the command is working by itself but not when used in the script Commented Aug 22, 2013 at 7:22
  • @Jigar There's no error code, its just that nothing is getting returned. Commented Aug 22, 2013 at 7:23

3 Answers 3

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);
?>
Sign up to request clarification or add additional context in comments.

6 Comments

I can't install any packages on these machines. Is there any other way around this?
Well, if you can create PHP source files on your machines, you can install phpseclib, because that's just a bunch of PHP files as well.
Is it possible to the login with SSH keys instead of using a hardcoded password?
Easily. Check out their examples.
Worked perfectly with the SSH key, too.
|
0

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

$str = "ssh -p $port $username@$server $command";

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.