linux安装ssh2,php远程登录服务器

1:安装libssh2

wget http://www.libssh2.org/download/libssh2-1.4.2.tar.gz

tar -xzvf  libssh2-1.4.2.tar.gz

cd libssh2-1.4.2

./configure --prefix=/vol/usr/local/lamp/libssh2             (libssh2的安装目录)

make

make install

2:安装ssh2

wget http://pecl.php.net/package/ssh2-0.13.tgz

tar -xzvf ssh2-0.13.tgz

cd ssh2-0.13

wget http://pecl.php.net/get/ssh2-0.13.tgz

tar zxvf ssh2-0.13.tgz

phpize

./configure --with-php-config=/usr/local/php/bin/php-config --prefix=/vol/usr/local/lamp/ssh2 --with-ssh2=/vol/usr/local/lamp/libssh2

make

make install

在php.ini配置文件中添加ssh2扩展:extension=ssh2.so

参考链接:https://my.oschina.net/u/2505940/blog/1587767

/**
     * 远程登陆服务器
     */
    private function remote_login($cmd='', $config=[]) {
        if (empty($config)) {
            return false;
        }

// 连接服务器
        $connection=ssh2_connect($config['host'], $config['port']);
        
        // 身份验证
        ssh2_auth_password($connection, $config['username'], $config['password']);

        // 执行命令
        $ret=ssh2_exec($connection, $cmd);

        // 获取结果
        stream_set_blocking($ret, true);
        
        // 返回结果
        return stream_get_contents($ret);
    }
    
    /**
     *  远程操作服务器
     */
    public function test() {
        $config['host'] = 'xxx'; //服务器的ip
        $config['port'] = 22;
        $config['username'] = 'root'; //用户名
        $config['password'] = 'xxxx'; //密码
        
        $cmd = 'cd /&&ls';
        
        $res = $this->remote_login($cmd, $config);
        echo "<pre>";var_dump($res);
        
    }

猜你喜欢

转载自blog.csdn.net/lorraine_40t/article/details/81872039