Advertisement
Guest User

Untitled

a guest
Jan 12th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. /**
  2. * connect mysql using ssh port forwarding
  3. *
  4. **/
  5. 'use strict';
  6.  
  7. const mysql = require('mysql');
  8. let dbConfig = {
  9. host: 'dbhost',
  10. user: 'user_name',
  11. password: 'password',
  12. database: 'db_name',
  13. port: 3306
  14. };
  15.  
  16. function _forwardingConnect(dbParam, callback)
  17. {
  18. const freeport = require('freeport');
  19. const tunnel = require('tunnel-ssh');
  20. const fs = require('fs');
  21. let portForwardingConfig = {
  22. username: 'ssh_user_name',
  23. port: 22,
  24. host: "0.0.0.0", // SSH IP
  25. privateKey: fs.readFileSync('./id_rsa'),
  26. dstHost: dbParam.host,
  27. dstPort: 3306,
  28. srcHost: 'localhost',
  29. srcPort: null,
  30. localHost: 'localhost',
  31. localPort: null,
  32. keepAlive: true
  33. };
  34. dbParam.host = "localhost";
  35. freeport((err, freePort) => {
  36. // change port
  37. portForwardingConfig.srcPort = freePort;
  38. portForwardingConfig.localPort = freePort;
  39. dbParam.port = freePort;
  40. // tunneling
  41. tunnel(portForwardingConfig, (sshTunnel) => {
  42. var _dbConn = mysql.createConnection(dbParam);
  43. _dbConn.connect();
  44. callback(_dbConn);
  45. });
  46. });
  47. };
  48.  
  49. const getConn = ((callback) => {
  50. _forwardingConnect(dbConfig, callback);
  51. });
  52.  
  53. exports.getConn = getConn;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement