Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * connect mysql using ssh port forwarding
- *
- **/
- 'use strict';
- const mysql = require('mysql');
- let dbConfig = {
- host: 'dbhost',
- user: 'user_name',
- password: 'password',
- database: 'db_name',
- port: 3306
- };
- function _forwardingConnect(dbParam, callback)
- {
- const freeport = require('freeport');
- const tunnel = require('tunnel-ssh');
- const fs = require('fs');
- let portForwardingConfig = {
- username: 'ssh_user_name',
- port: 22,
- host: "0.0.0.0", // SSH IP
- privateKey: fs.readFileSync('./id_rsa'),
- dstHost: dbParam.host,
- dstPort: 3306,
- srcHost: 'localhost',
- srcPort: null,
- localHost: 'localhost',
- localPort: null,
- keepAlive: true
- };
- dbParam.host = "localhost";
- freeport((err, freePort) => {
- // change port
- portForwardingConfig.srcPort = freePort;
- portForwardingConfig.localPort = freePort;
- dbParam.port = freePort;
- // tunneling
- tunnel(portForwardingConfig, (sshTunnel) => {
- var _dbConn = mysql.createConnection(dbParam);
- _dbConn.connect();
- callback(_dbConn);
- });
- });
- };
- const getConn = ((callback) => {
- _forwardingConnect(dbConfig, callback);
- });
- exports.getConn = getConn;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement