0

我是 PHP 编码的新手,我正在编写新的简单脚本,但是当我输入这段代码时,我得到空白页,有人能告诉我这段代码有什么问题吗?

<?php
if($_POST) {
$host = $_POST['host'];
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
if(!($con = ssh2_connect("127.0.0.1", "22")))
{
    echo "fail: unable to establish connection";
}
else
{
    if(!ssh2_auth_password($con, "root", "password"))
    {
        echo "fail: unable to authenticate ";
    }
    else
    {

        $stream = ssh2_exec($con, "".$host."");
            stream_set_blocking($stream, true);
        $item = "";
        while ($input = fread($stream,4096)) {
               $item .= $input;
        }
        echo $item;
    }
}

?>

对不起我的坏 CN

4

3 回答 3

2

使用phpseclib,一个纯 PHP SSH2 实现,您可能会有更好的运气。例如。

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

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

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

如果您想让命令在获得输出之前运行一段时间,您可以这样做$ssh->setTimeout(1)。所以你可以ping 127.0.0.1在 Linux 上做,它不会停止,但 phpseclib 仍然会在一分钟后停止。

于 2015-02-03T17:10:24.763 回答
0

我工作了几天以使 ssh2 在 PHP [www 上的专用服务器管理面板] 中工作,但我没有找到任何解决输出问题的方法。唯一有效(但这仅对某些脚本来说已经足够了)是在 'exec' 和 'read' 之间休眠一段时间:

$stream = ssh2_exec($connection->conn, 'pgrep screen');
stream_set_blocking($stream, true);
// sleep 0.5 sec, this trick won't work for commands that execution time is unpredictable
usleep(500000);
$line = '';
while($get = fgets($stream))
{
    $line .= $get;
}
echo $line;
于 2015-02-02T20:50:49.957 回答
0

也许它不是 OP 的问题,但标题说明了 php sshpass ssh,值得添加一个简单的 php 示例,使用sshpassand sshwith exec()

$ssh_host = "127.0.0.1";
$ssh_port = "22";
$ssh_user = "root";
$ssh_pass = "password";
$command = "uname -a";
$connection = "/usr/bin/sshpass -p $ssh_pass /usr/bin/ssh -p $ssh_port -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null $ssh_user@$ssh_host";
$output = exec($connection." ".$command." 2>&1");
echo "Output: $output";
于 2016-11-30T01:49:41.597 回答