Created
July 21, 2018 05:03
-
-
Save yuta17/330ea5bfd3611b3b9255db44c01f2c4c to your computer and use it in GitHub Desktop.
connect database (tunnel ssh) by nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| '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