通过 SSH 连接 MySQL 时遇到问题

2024-04-07

我正在本地 OS X 计算机上运行 Node Express 网站。

我需要 ssh 到远程 mysql 数据库,以便我可以开始针对它编写查询。

现在,当我通过 OS X Yosemite 终端执行此操作时,我可以 ssh 到云中的远程服务器(运行 mysql 数据库)。

但我没有成功地尝试使用 node-mysql 和tunnel-ssh 节点中间件在代码中完成此操作。

我的代码可以运行,但在 Webstorm 中调试我的 Express 应用程序时除了 GET 之外并没有真正出错。

一些事实:

  • 我可以使用以下命令从 OS X SSH 到 mySQL:

    ssh -L 3306:127.0.0.1:3306 ourCloudServerName.net MyUserNameHere

  • 然后我可以使用以下命令连接到 mySQL:

    mysql -h localhost -p -u myUserNameHere

  • 当我在 mysql 命令提示符下输入 SHOW GLOBAL VARIABLES LIKE 'PORT' 时,我发现服务器(或数据库,我猜这意味着......不确定)正在端口 3306 上运行

  • 我正在通过 Webstorm 10.0.3 进行调试 这意味着我正在调试我的 Node Express 应用程序,它的启动方式如下:

    变量端口= 3000;

    app.set('端口', 端口);

    app.listen(app.get('端口'), function(){ console.log('Express Web 服务器正在侦听端口 ' + app.get('port')); })

    • 我可以在 Chrome 中通过 localhost:3000 运行我的 Express 应用程序

现在这是我第一次尝试使用node-mysql和tunnel-ssh

mysqlConfig.js

var databaseConfig = module.exports = function(){};

 module.exports = {

    mySQLConfig: {
       host: '127.0.0.1',
       username: 'root',
       password: 'rootPassword',
       database: 'SomeDatabaseName',
       port: 3306,
       timeout: 100000
    },

    sshTunnelConfig: {
       username: 'myusername',
       password: 'mypassword',
       host: 'ourCloudServerName\.net',
       port: 22,
       //localPort: 3306, //4370
       //port: 3333,
       //localPort: 4370,
       dstPort: 3306,
       srcHost: 'localhost',
       dstHost: 'localhost',
       localHost: 'localhost'
    }
 };

连接.js

 var mysql = require('mysql'),
    config = require('./mysqlConfig'),
    tunnel = require('tunnel-ssh');


var connection = module.exports = function(){};

createDBConnection = function(){
    var mysqlConnection = mysql.createConnection({
        host: config.mySQLConfig.host,
        user: config.mySQLConfig.username,
        password: config.mySQLConfig.password,
        database: config.mySQLConfig.database,
        connectTimeout: config.mySQLConfig.timeout
    });

    return mysqlConnection;
};


connection.invokeQuery = function(sqlQuery){

    var data = undefined;

    var sshTunnel = tunnel(config.sshTunnelConfig, function(error, result) {

        var sqlConnection = createDBConnection();

        sqlConnection.connect(function (err) {
            console.log(err.code);
        });
        sqlConnection.on('error', function (err) {
            console.log(err.code);
        });

        data = sqlConnection.query({
            sql: sqlQuery,
            timeout: config.mySQLConfig.timeout
        }, function (err, rows) {

            if (err && err.code) {
                console.log("error code: " + err.code)
            }
            if (err) {
                console.error("error stack: " + err.stack)
            }
            ;

            if (rows) {
                console.log("We have Rows!!!!!!")
            }
        });

        sqlConnection.destroy();
    });

    return data;
};

router/index.js

var connection = require('../config/database/connection');
var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
    var sqlStatement = "Select top 10 from someTable";

    var rows = connection.invokeQuery(sqlStatement);
});

module.exports = router;

因此,我尝试在 Webstorm 中进行调试,但我要么从来没有真正在控制台上打印出好的错误,要么即使打印了,它也是一个通用的节点错误,例如:我可能有一个基本的代码问题和/或只是没有正确设置值或正确使用中间件,我只是不知道,它在调试过程中并没有告诉我太多信息。我只知道:

1)我没有通过 ssh 连接到服务器。调试期间 ssh 服务器对象中的连接显示 0

2)mysql连接对象显示已断开连接,从未连接过

3)在运行 Express 网站时,我也在 Webstorm 中遇到此节点错误,该错误没有告诉我杰克:

什么连接被拒绝,我通过本地主机端口 3000 运行这个网站。这是说它无法连接到 ssh 吗?我在这里不知道。这并不总是出现或发生,这是一个间歇性错误,可能只是一个网络风暴调试问题,我只需要再次运行调试,通常会消失......但可能是相互关联的,没有线索。

这是我在调试期间检查时配置对象的内容

在tunnel-ssh/index.js 中,第 70 行返回它尝试创建的服务器,我看到没有 ssh 连接:

更新 - 根据答案的建议


如果您需要做的只是从应用程序内部建立 MySQL 连接隧道,那么这实际上可以简化。这mysql2模块(更好)支持传递自定义流以用作数据库连接,这意味着您不必启动本地 TCP 服务器并侦听通过隧道的连接。

这是一个使用的示例mysql2 https://github.com/sidorares/node-mysql2 and ssh2 https://github.com/mscdex/ssh2:

var mysql2 = require('mysql2');
var SSH2Client = require('ssh2').Client;

var sshConf = {
  host: 'ourCloudServerName.net',
  port: 22,
  username: 'myusername',
  password: 'mypassword',
};
var sqlConf = {
  user: 'root',
  password: 'rootPassword',
  database: 'SomeDatabaseName',
  timeout: 100000
};

var ssh = new SSH2Client();
ssh.on('ready', function() {
  ssh.forwardOut(
    // source IP the connection would have came from. this can be anything since we
    // are connecting in-process
    '127.0.0.1',
    // source port. again this can be randomized and technically should be unique
    24000,
    // destination IP on the remote server
    '127.0.0.1',
    // destination port at the destination IP
    3306,
    function(err, stream) {
      // you will probably want to handle this better,
      // in case the tunnel couldn't be created due to server restrictions
      if (err) throw err;

      // if you use `sqlConf` elsewhere, be aware that the following will
      // mutate that object by adding the stream object for simplification purposes
      sqlConf.stream = stream;
      var db = mysql2.createConnection(sqlConf);

      // now use `db` to make your queries
    }
  );
});
ssh.connect(sshConf);

当然,您需要扩展这个示例,在 ssh 和 mysql 级别添加错误处理,以防由于某种原因而消失(例如 TCP 连接被切断或 ssh/mysql 服务被停止)。通常您只需添加error事件处理程序ssh and db处理大多数情况,尽管您可能想听end事件也知道您何时需要重新建立其中一个/两个ssh and db连接。

此外,在 ssh 和 mysql 级别配置 keepalive 可能是明智的。ssh2有几个保活选项 https://github.com/mscdex/ssh2#client-methods其行为就像 OpenSSH 客户端的 keepalive 选项。 为了mysql2,通常我所做的就是打电话db.ping()在某个间隔。您可以传入一个回调,当服务器响应 ping 时,该回调将被调用,这样您就可以could使用一个额外的计时器,该计时器在回调执行时被清除。这样,如果回调未执行,您可以尝试重新连接。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 SSH 连接 MySQL 时遇到问题 的相关文章

随机推荐