php ssh2_exec 不执行 'su' 命令

标签 php ssh

我在 php 的 ssh2 上玩得很开心。(!)

我正在通过 ssh 连接到本地主机(运行 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 - a pure PHP SSH implementation - 反而。以下是您如何使用它执行 su 操作:

<?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]');
?>

关于php ssh2_exec 不执行 'su' 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5732990/

相关文章:

php - 如何调用包含连续数字的变量?

PHP将图像转换为二进制文件测试

php - 我如何将此 UTF-8 字符串编码为 ASCII 以将其插入 latin1 数据库?

ssh - 使用内置命令通过 PuTTY 访问虚拟机 "vagrant ssh"

python - 如何在没有 pip 和 brew 的 ssh hadoop 系统(沙箱)上安装 python 3?

ssh - 如何防止与dataproc上的SOCKS的“连接被拒绝”?

php - Symfony2 : how to set the host/base url in CLI scripts

php - php中不刷新提交

mysql - 使用 ssh 导入 .sql 文件

ssh - 在非 22 端口的 Amazon EC2 实例上运行 ssh