LoginSignup
1
0

More than 5 years have passed since last update.

TypeScriptでSSHポート転送する

Posted at

JavaScript (TypeScript) でSSHポート転送するには tunnel-ssh を使うとよい。tunnel-sshssh2 のポート転送機能を使いやすくしたライブラリである。

実装例

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();
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0