创建交互式ssh2终端窗口

时间:2014-10-23 09:13:25

标签: php ssh libssh2

下面的代码工作,它完美地返回我连接到SSH服务器的用户名。是否可以创建某种交互式shell,我可以自己发送命令。就像Mac上的黑色终端窗口一样。我已经在ssh2_shell函数上看到了一些文档,您可以在其中指定终端窗口的宽度和高度,但无法正常工作。

$server['ip'] = "127.0.0.1";
$server['sshport'] = 22;
$server['user'] = "myUsername";
$server['pw'] = "myPassword!";

$command = "whoami";

if($ssh = ssh2_connect($server['ip'], $server['sshport'])) {
    if(ssh2_auth_password($ssh, $server['user'], $server['pw'])) {
        $stream = ssh2_exec($ssh, $command);
        stream_set_blocking($stream, true);
        $data = "";
        while($buffer = fread($stream, 4096)) {
            $data .= $buffer;   
        }
        fclose($stream);
        print $data;
    } else {
        echo "User or password is incorrect!";
    }
} else {
    echo "Could not connect to the ssh server!";    
}

1 个答案:

答案 0 :(得分:2)

我不认为可能与libssh2有关。我知道在PHP中这样做的唯一方法是使用phpseclib:

http://phpseclib.sourceforge.net/ssh/examples.html#top

示例:

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

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

$ansi = new File_ANSI();

$ansi->appendString($ssh->read('username@username:~$'));
$ssh->write("top\n");
$ssh->setTimeout(5);
$ansi->appendString($ssh->read());
echo $ansi->getScreen(); // outputs HTML
?>