php使用ssh2来操作服务器执行命令

来源:赵克立博客 分类: PHP 标签:Linux命令发布时间:2019-12-24 21:28:06最后更新:2019-12-25 09:02:21浏览:732
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2019-12-25 09:02:21
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章

方法一(推荐)

private function runSSH($cmdstr)
{
    //服务器信息
    $host   = '172.18.0.1';
    $user   = 'root';
    $passwd = 'yB1TYzIZhWrn19zV';

    //链接远程服务器

    $connection = @ssh2_connect($host, 22);
    if (!$connection) {
        return '';
        die('Connection failed.');
    }
    //可否通过密码连接
    $auth_methods = ssh2_auth_none($connection, $user);
    if (!in_array('password', $auth_methods)) {
        return '';
        die('Unable to login to remote server by password.');
    }

    //验证密码
    if (!ssh2_auth_password($connection, $user, $passwd)) {
        return '';
        die('Password error.');
    }
    $stream = ssh2_exec($connection, $cmdstr);
    stream_set_blocking($stream, true);
    $str = stream_get_contents($stream);
    fclose($stream);
    return $str;
}


方法二

//服务器信息
$host   = '10.10.10.10';
$user   = 'root';
$passwd = 'dD*********JWv07G';

//链接远程服务器

$connection = @ssh2_connect($host, 22);
if (!$connection) {
    die('Connection failed.');
}
//可否通过密码连接
$auth_methods = ssh2_auth_none($connection, $user);
if (!in_array('password', $auth_methods)) {
    die('Unable to login to remote server by password.');
}

//验证密码
if (!ssh2_auth_password($connection, $user, $passwd)) {
    die('Password error.');
}
$shell = ssh2_shell($connection, 'xterm');
//由于一些模糊的原因,在命令之后,您需要睡眠以确保命令已经到达服务器并正在运行
//上面是其它人测试时加的,我测试后发现不睡眠也可以取到信息,这里标记一下
//sleep(2);
fwrite($shell, 'ls -al' . PHP_EOL);
//sleep(5);
while ($line = fgets($shell)) {
    echo $line . '<br />';
}



微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python