cakePHP 2.x 使用密钥连接到远程数据库

问题描述 投票:0回答:2

我需要连接到不同服务器上的 mysql 数据库,我有连接到服务器的 RSA 密钥,并且我也有连接到数据库所需的所有凭据,并且使用以下代码,我能够得到完美连接

try {
    $this->db = new PDO("mysql:host=$this->host;port=$this->port;dbname=$this->dbname", $this->sqlUser, $this->sqlPass);
} catch (Exception $e) {
    shell_exec("ssh -i /path/to/rsa/key/the_key [email protected] -L3307:localhost:3306 -N");
};

try {
    $this->db = new PDO("mysql:host=$this->host;port=$this->port;dbname=$this->dbname", $this->sqlUser, $this->sqlPass);
} catch (Exception $e) {
    die($e->getMessage() . " (line:" . __LINE__ . ")");
};

但是,我正在使用 cakePHP 2.x 构建应用程序,如何使用 cakePHP 的配置连接到远程服务器和数据库?

谢谢

database cakephp-2.1
2个回答
1
投票

好吧,我设法通过在 app/Model/DataSource/Database 下创建一个名为 FarAwayMysql.php 的扩展类来做到这一点

App::uses('DboSource', 'Model/Datasource');

class FarAwayMysql extends DboSource {
public $description = "Faraway MySQL DBO Driver";

protected $_baseConfig = array(
    'persistent' => true,
    'host' => 'localhost',
    'login' => 'root',
    'password' => '',
    'database' => 'cake',
    'port' => '3306',
    'rsa' => '',
    'remote_username' => '',
    'remote_ip' => ''
);
protected $_connection = null;

protected $_useAlias = true;

public function connect() {
    $config = $this->config;
    $this->connected = false;
    try {
        $flags = array(
            PDO::ATTR_PERSISTENT => $config['persistent'],
            PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );
        if (!empty($config['encoding'])) {
            $flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $config['encoding'];
        }
        if (empty($config['unix_socket'])) {
            $dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}";
        } else {
            $dsn = "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
        }
        $this->_connection = new PDO(
            $dsn,
            $config['login'],
            $config['password'],
            $flags
        );
        $this->connected = true;
    } catch (PDOException $e) {
        echo "ssh -i {$config['rsa']} {$config['remote_username']}@{$config['remote_ip']} -L3307:{$config['host']}:3306 -N";
        shell_exec("ssh -i {$config['rsa']} {$config['remote_username']}@{$config['remote_ip']} -L3307:{$config['host']}:3306 -N");
    }


    try {
        $flags = array(
            PDO::ATTR_PERSISTENT => $config['persistent'],
            PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );
        if (!empty($config['encoding'])) {
            $flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $config['encoding'];
        }
        if (empty($config['unix_socket'])) {
            $dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}";
        } else {
            $dsn = "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
        }
        $this->_connection = new PDO(
            $dsn,
            $config['login'],
            $config['password'],
            $flags
        );
        $this->connected = true;
    } catch (PDOException $e) {             
        throw new MissingConnectionException(array(
            'class' => get_class($this),
            'message' => $e->getMessage()
        ));
    }

    $this->_useAlias = (bool)version_compare($this->getVersion(), "4.1", ">=");

    return $this->connected;
}
}

添加 3 个新配置

protected $_baseConfig = array(
    'persistent' => true,
    'host' => 'localhost',
    'login' => 'root',
    'password' => '',
    'database' => 'cake',
    'port' => '3306',
    'rsa' => '',
    'remote_username' => '',
    'remote_ip' => ''
);

然后在你的 app/Config/database.php 上,它会是

public $faraway = array(
    'datasource' => 'Database/FarAwayMysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'faraway_username',
    'password' => 'faraway_password',
    'database' => 'faraway_db_name',
    'port' => '',
    'rsa' => 'path/to/rsa/key',
    'remote_username' => 'your_username',
    'remote_ip' => 'your.ip.address'
);

1
投票

感谢您的帖子。我使用

PostgreSQL
而不是
MySQL
,因此做了一些调整。其中一些也可能与
MySQL
相关。

  1. 当 shell_exec'ing 时,将输出重定向到

    /dev/null
    并在后台运行。端口也从
    3306/3307
    更改为
    5432/5433

    shell_exec("ssh -i {$config['rsa']} {$config['remote_username']}@{$config['remote_ip']} -L5433:{$config['host']}:5432 - N > /dev/null &")

  2. FarAwayPostgres.php
    如下

    真的, '主机' => '本地主机', '登录' => '根', '密码' => '', '数据库' => '蛋糕', '端口' => '5432', 'rsa' => '', '远程用户名' => '', 'remote_ip' => '', 'sslmode' => '允许', '模式' => '公共', '标志' => 数组() ); 受保护的$_connection = null; 受保护的$_useAlias = true; 公共函数连接(){ $config = $this->config; $this->已连接 = false; $flags = $config['flags'] + 数组( PDO::ATTR_PERSISTENT => $config['持久'], PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); 尝试 { 如果(空($config['unix_socket'])){ $dsn = "pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']};sslmode={$config['sslmode ']}"; } 别的 { $dsn = "pgsql:unix_socket={$config['unix_socket']};dbname={$config['database']}"; } $this->_connection = new PDO( $dsn, $config['login'], $config['password'], $flags); $this->已连接 = true; } catch (PDOException $e) { $cmd="ssh -i {$config['rsa']} {$config['remote_username']}@{$config['remote_ip']} -L5433:{$config['host']}:5432 - N > /dev/null &"; shell_exec($cmd); 睡眠(3); } 尝试 { 如果(空($config['unix_socket'])){ $dsn = "pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']};sslmode={$config['sslmode ']}"; } 别的 { $dsn = "pgsql:unix_socket={$config['unix_socket']};dbname={$config['database']}"; } $this->_connection = new PDO( $dsn, $config['login'], $config['password'], $flags); $this->已连接 = true; } catch (PDOException $e) { 抛出新的 MissingConnectionException(数组( 'class' => get_class($this), '消息' => $e->getMessage() )); } 返回 $this->已连接; } }

注意如何插入三秒睡眠,以便与数据库的连接尝试等待 ssh 完成。

最后,

database.php

<?php
class DATABASE_CONFIG {

        public $default = array(
                'datasource'      => 'Database/FarAwayPostgres',
                'persistent'      => false,
                'host'            => 'localhost',
                'port'            => '5433',
                'login'           => 'postgres',
                'password'        => '',
                'database'        => 'remote_db',
                'rsa'             => '/var/www/.ssh/id_rsa',
                'remote_username' => 'root',
                'remote_ip'       => 'remote_server',
                'prefix'          => '',
                'encoding'        => 'utf8',
        );

私钥

id_rsa
位于 Apache 的主目录中,可由
Apache
读取。

最后,在使用之前,请执行以下操作:

su -m apache
ssh -i /var/www/.ssh/id_rsa root@remote_server

为了更新

known_hosts

© www.soinside.com 2019 - 2024. All rights reserved.