繁体   English   中英

php ssh2_exec没有执行'su'命令

[英]php ssh2_exec not executing 'su' command

我用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);
                }
            }
        }
    }

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

我得到的输出是:

okay: logged in...
Resource id #3
after stream_set_blocking
data len: 0

在此先感谢任何帮助:)

您应该尝试最新的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]');
?>

也许尝试像bash -c susu rootbash -c "su root"

您只需在执行“su”命令时附加超级用户密码即可。 您可以对代码进行以下修改。

$cmd = "su";
$cmd = "echo '" . $sshPassword . "' | sudo -S " . $cmd;
if (!($stream = ssh2_exec($con, $cmd))) { 
... 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM