我正在创建一个节点应用程序,它通过SSH将本地端口映射到远程计算机上的端口。
在shell命令中,我可以这样做:
ssh -fN -l username -i ~/.ssh/myKey.pem -L 9999:localhost:27017 1.2.3.4
打开到1.2.3.4的持久ssh连接,并将Remote上的27017端口映射到我的Local上的9999。
但是我怎样才能在nodejs中实现-L动作 我正在使用npm ssh2包来执行ssh连接。
答案 0 :(得分:1)
您可以使用以下示例执行反向ssh隧道。我假设远程主机在示例中使用公钥和私钥认证,如果不是这种情况请相应地更改示例。不要忘记你必须侦听你要转发请求的本地端口。
var path = require('path');
var fs = require('fs');
var Connection = require('ssh2');
var net = require('net')
var c
var username = 'username'
var hostname = 'remote host IP or domain name'
var port = 22
var privKey = path.join(__dirname, 'path to private key', 'filename')
var localAddr = 'localhost'
var localPort = 'local port on which you want to receive the requests'
var remotePort = 'remote port that you want to forward'
var remoteAddr = '0.0.0.0'
c = new Connection()
c.on('connect', function() {
console.log('Connection :: connect')
})
c.on('tcp connection', function(info, accept, reject) {
console.log('TCP :: INCOMING CONNECTION: ' +
require('util').inspect(info));
var stream = accept()
var socket
stream.on('data', function(data) {
console.log('TCP :: DATA: ' + data);
})
stream.on('end', function() {
console.log('TCP :: EOF');
})
stream.on('error', function(err) {
console.log('TCP :: ERROR: ' + err);
})
stream.on('close', function(had_err) {
console.log('TCP :: CLOSED', had_err ? 'had error' : '');
})
stream.pause()
socket = net.connect(localPort, localAddr, function () {
stream.pipe(socket);
socket.pipe(stream);
stream.resume();
})
})
c.on('ready', function() {
console.log('Connection :: ready')
c.forwardIn(remoteAddr, remotePort, function(err) {
if (err) { throw err }
console.log('Forwarding connections from remote server on port 7070 to
node socket!');
})
})
c.on('error', function(err) {
console.log('Connection :: error :: ', err)
})
c.on('end', function() {
console.log('Connection :: end')
})
c.on('close', function(had_error) {
console.log('Connection :: close', had_error ? 'had error' : '')
})
var obj = {
host: hostname,
port: port,
username: username,
privateKey: fs.readFileSync(privKey).toString()
}
c.connect(obj)