JavaScript (TypeScript) でSSHポート転送するには tunnel-ssh を使うとよい。tunnel-ssh は ssh2 のポート転送機能を使いやすくしたライブラリである。
実装例
Tunnel.ts
import * as tunnel from 'tunnel-ssh';
interface Config {
host: string;
port: number;
username: string;
password: string;
localPort: number;
dstHost: string;
dstPort: number;
}
class Tunnel {
private static connections: any[] = new Array<any>();
public static async createConnection(config: Config) {
var tnl = tunnel(config, (error, tnl) => {
if (error) {
throw new Error(error);
} else {
this.connections.push(tnl);
}
});
}
public static async closeAllConnections() {
this.connections.forEach(tnl => {
tnl.close();
});
}
}
export default Tunnel;
使い方
await Tunnel.createConnection({
host: 'sshd.example.com',
port: 22,
username: 'username',
password: 'password',
localPort: 10080,
dstHost: 'dst.example.com',
dstPort: 80
});
// ここでコネクションを使う通信処理を行う。
await Tunnel.closeAllConnections();