php ssh2_exec没有执行'su'命令

Joe*_*Joe 4 php ssh

我用ssh2 for php很开心.(!)

我正在通过ssh-ing进入localhost(运行ubuntu)进行测试.我已经设法用我的用户名(不是root)连接和验证,并且一些命令(比如'ls'返回一些信息,这很有希望.绝对可以到达某个地方.

我希望接下来能做的是发出'su'命令,然后给出root密码.

我没有收到错误,并返回资源,但流中似乎没有数据.(我有点期待'密码:'提示).我无法直接使用root密码进行身份验证,因为ssh禁用了该密码.

有没有理由为什么'su'会带回一些文字,你觉得呢?

我应该期待'密码:'提示回来吗?

这是我的代码:

function changeServerPassword( $ip, $port, $sshUser, $sshPassword, $rootPassword, $newRootPassword, $newSSHPassword = false) {
        // login to server using $sshUser and $sshPassword
        // su as root and enter $rootPassword
        // if any of the above steps fail, return with appropriate error message
        if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
        // log in 
        // Do I have to make sure that port is a number?
        if(!($con = ssh2_connect($ip, $port))){
            echo "fail: unable to establish connection\n";
        } else {
            // try to authenticate with username root, password secretpassword
            if(!ssh2_auth_password($con, $sshUser, $sshPassword)) {
                echo "fail: unable to authenticate\n";
            } else {
                // alright, we're in!
                echo "okay: logged in...<br />";

                // 
                if (!($stream = ssh2_exec($con, "su"))) {
                    echo "fail: unable to execute command\n";
                } else {
                    echo $stream."<br />";
                    // collect returning data from command
                    stream_set_blocking($stream, true);
                    echo "after stream_set_blocking<br />";
                    $data = "";
                    while ($buf = fread($stream,4096)) {
                        $data .= $buf;
                    }
                    echo "data len: " . strlen($data) . "<br />";
                    echo $data."<br />";
                    fclose($stream);
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

借鉴了http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ 尊重.

我得到的输出是:

okay: logged in...
Resource id #3
after stream_set_blocking
data len: 0
Run Code Online (Sandbox Code Playgroud)

在此先感谢任何帮助:)

小智 5

您应该尝试最新的SVN版本的phpseclib - 一个纯PHP SSH实现 - 而不是.以下是你如何做到这一点:

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

$ssh = new Net_SSH2('localhost', 22);
$ssh->login('username', 'password');

$ssh->read('[prompt]');
$ssh->write("su - user\n");
$ssh->read('Password:');
$ssh->write("Password\n");
echo $ssh->read('[prompt]');
?>
Run Code Online (Sandbox Code Playgroud)