Skip to content

Instantly share code, notes, and snippets.

@yuta17
Created July 21, 2018 05:03
Show Gist options
  • Select an option

  • Save yuta17/330ea5bfd3611b3b9255db44c01f2c4c to your computer and use it in GitHub Desktop.

Select an option

Save yuta17/330ea5bfd3611b3b9255db44c01f2c4c to your computer and use it in GitHub Desktop.
connect database (tunnel ssh) by nodejs
'use strict';
const https = require('https');
const mysql = require('mysql2');
const ssh2Client = require('ssh2').Client;
const ssh = new ssh2Client();
const dbHost = '';
const dbUser = '';
const dbPassword = '';
const dbName = '';
const sshConfig = {
host: '',
port: 22,
username: '',
privateKey: require('fs').readFileSync(require('path').join(__dirname, '')),
};
const mysqlConfig = {
user: dbUser,
password: dbPassword,
database: dbName,
};
ssh.on('ready', () => {
ssh.forwardOut(
'127.0.0.1',
24000,
dbHost,
3306,
(err, stream) => {
if (err) throw console.log(err);
mysqlConfig.stream = stream;
const db = mysql.createConnection(mysqlConfig);
db.connect();
db.query('SELECT * from projects LIMIT 1', (err, result, fields) => {
console.log(result);
});
db.end();
});
});
ssh.connect(sshConfig);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment