Created
March 23, 2021 14:32
-
-
Save emmanuelnk/d7ce39d317805f489b5045b4b1ca8026 to your computer and use it in GitHub Desktop.
Forward SSH port in Node.js
This file contains 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
import sshClient from 'ssh2-promise' | |
const config = { | |
database: { | |
host: process.env.DB_HOST, | |
username: process.env.DB_USER, | |
password: process.env.DB_PASSWORD, | |
port: process.env.DB_PORT, | |
databaseName: process.env.DB_NAME, | |
}, | |
ssh: { | |
host: process.env.SSH_HOST, | |
port: process.env.SSH_PORT, | |
identity: process.env.SSH_KEY_PATH, | |
// username: process.env.SSH_USER, | |
// password: process.env.SSH_PASSWORD, | |
} | |
} | |
export const connectSHHTunnel = async (): Promise<void> => { | |
const ssh = new sshClient(config.ssh) | |
// connect tunnel | |
try { | |
await ssh.connect() | |
console.log(`SSH connection established to ${config.ssh.host}:${config.ssh.port}`) | |
} catch (error) { | |
console.error('[ssh.connect]', error) | |
} | |
// forward local port | |
try { | |
await ssh.addTunnel({ | |
remoteAddr: config.database.host, | |
remotePort: Number(config.database.port), | |
localPort: Number(config.database.port) | |
}) | |
console.log(`Remote ${config.database.host}:${config.database.port} forwarded to localhost:${config.database.port}`) | |
} catch(error) { | |
console.error('[ssh.addTunnel]', error) | |
} | |
ssh.on('close', async() => { | |
console.log('client disconnected by server. Reconnecting...') | |
await connectSHHTunnel() | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment