Execute a shell command through ssh using PHP

后端 未结 3 1035
逝去的感伤
逝去的感伤 2020-12-17 07:10

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.

相关标签:
3条回答
  • 2020-12-17 07:36

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

    $str = "ssh -p $port $username@$server $command";
    
    0 讨论(0)
  • 2020-12-17 07:48

    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);
    ?>
    
    0 讨论(0)
  • 2020-12-17 07:58

    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.

    0 讨论(0)
提交回复
热议问题