[英]Node SSH2 double ssh connection
我正在尝试通过带有节点的 ssh 进行 2 次跳转,最终目标是连接到数据库。 这个想法是:
local ->ssh-> bastion1 ->ssh-> bastion2
我不太明白这一点,我在第二个 ssh 上不断收到错误error ECONNREFUSED xxxxxx:22
。
我当前的代码如下所示:
const Client = require('ssh2').Client;
doubleBastion (sshConfig, dbConfig, debug = false) {
dbConfig = this.addDefaults(dbConfig);
return new Promise((resolve, reject) => {
connOne = new Client();
connOne.on('ready', () => {
console.log('SSH 1 CONNECTED!');
connTwo = new Client();
connTwo.on('ready', () => {
console.log('SSH 2 CONNECTED!');
// establish db connection
}).connect({
passphrase: 'thepassword',
host: 'x.x.x.x',
user: 'ubuntu',
privateKey: sshConfig.key
});
}).connect(sshConfig);
});
}
关于如何使这项工作的任何想法?
您可以在 Node 中使用 ssh2 进行双跳
为隧道和目标服务器定义 ssh 凭据
const tunnelSSH = {
host: '192.168.70.169',
username: 'username',
password: 'password',
}
const destinationSSH = {
host:'192.168.70.170',
port:22,
username: 'username',
password: 'password'
}
const portforwardConfig = {
srcHost: '127.0.0.1', // source host
srcPort: 22, // source port
dstHost: destinationSSH.host, // destination host
dstPort: destinationSSH.port // destination port
};
定义通用函数来执行 ssh 并在目标服务器中执行命令
const sshHoping = function(forwardConfig, tunnelSSH, destinationSSH, command) { return new Promise((resolve,reject) =>{
const ssh1 = new Client();
const ssh2 = new Client();
ssh1.on('ready', () => {
console.log('FIRST :: connection ready');
// Alternatively, you could use something like netcat or socat with exec()
// instead of forwardOut(), depending on what the server allows
ssh1.forwardOut(forwardConfig.srcHost, forwardConfig.srcPort, forwardConfig.dstHost, forwardConfig.dstPort, (err, stream) => {
if (err) {
console.log('FIRST :: forwardOut error: ' + err);
ssh1.end();
reject('FIRST :: forwardOut error: ' + err)
}
ssh2.connect({
sock: stream,
username: destinationSSH.username,
password: destinationSSH.password,
});
});
}).connect(tunnelSSH);
ssh2.on('ready', () => {
console.log('SECOND :: connection ready');
ssh2.exec(command, (err, stream) => {
if (err) {
console.log('SECOND :: exec error: ' + err);
ssh1.end();
reject('SECOND :: exec error: ' + err)
}
stream.on('close', () => {
ssh1.end(); // close parent (and this) connection
}).on('data', (data) => {
ssh1.end();
resolve(data.toString())
console.log(data.toString());
});
});
});
})}
拨打电话的主要功能
const doubleBastion = async(data) => {
const command = "free -m"
await sshHoping(portforwardConfig,tunnelSSH,destinationSSH, command).then(function(result){
console.log(result)
}).catch(function(e){
console.log("Error : "+e.message)
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.