Php两种调用ssh的方法

上一篇 / 下一篇  2016-08-16 09:18:38 / 个人分类:开发相关

 
1.用key方式
public function ssh_cmd($cmd)
{
    $content = '';
    $host = "192.168.146.180";
   
   $connection = ssh2_connect($host,22,array('hostkey'=>'ssh-rsa'));
    if (!$connection)
        die('Connection failed');
    else
    {
        if(ssh2_auth_pubkey_file($connection, 'root','/root/.ssh/id_rsa.pub','/root/.ssh/id_rsa'))
        {
            $stream = ssh2_exec($connection, $cmd);
            $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

            stream_set_blocking($stream, true);
            stream_set_blocking($errorStream, true);

            if ($stream === FALSE) 
                    die('Command exec failed!');
            else
                    $content = stream_get_contents($stream).stream_get_contents( $errorStream );

            fclose($stream);
            fclose( $errorStream );
        }
        else
        {
            die('Public Key Authentication Failed');
        }
    }
    return $content;
}

使用key方式时,需要在php执行服务器上,root用户执行ssh-keygen命令,生成建立安全信任关系的证书。
[root@Client root]# ssh-keygen -b 1024 -t rsa
把生成的 /root/.ssh/id_rsa.pub 中的内容,追加到 ssh连接的服务器 /root/.ssh/authorized_keys 文件后;
php执行服务器上,ssh连接测试:ssh -o GSSAPIAuthentication=no 192.168.146.180
连接成功,表示安全信任关系配置完成;

执行php过程中,如果提示:
Warning: ssh2_auth_pubkey_file(): Authentication failed for root using public key: Unable to open public key file
表示php执行用户无权限访问/root/.ssh/id_rsa.pub&id_rsa
解决方法可参照:http://www.php.net/manual/en/function.ssh2-auth-pubkey-file.php

另外创建一个目录来存放证书信息,如:
mkdir /home/.ssh
cp -af /root/.ssh/id_rsa /home/.ssh/      
cp -af /root/.ssh/id_rsa.pub /home/.ssh/
chmod 777 /home/.ssh -R
修改ssh2_auth_pubkey_file中路径位置,再重试;

      
2.用密码方式

public function ssh_cmd($cmd)
{
    $content = '';
    $host = "192.168.146.180";
    $hostuser = "root";
    $sshpasswd = "123456";
    $connection = ssh2_connect($host,22);

    if (!$connection)
            die('Connection failed');
    else
    {
        if(ssh2_auth_password($connection, $hostuser, $sshpasswd))
        {
            $stream = ssh2_exec($connection, $cmd);
            $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

            stream_set_blocking($stream, true);
            stream_set_blocking($errorStream, true);

            if ($stream === FALSE) 
                    die('Command exec failed!');
            else
                    $content = stream_get_contents($stream).stream_get_contents( $errorStream );

            fclose($stream);
            fclose( $errorStream );
        }
        else
        {
            die('Public Key Authentication Failed');
        }
    }
    return $content;
}
    

TAG: PHP ssh SSH 调用 方法 Php 两种

 

评分:0

我来说两句

Open Toolbar