OpenSSH でのポートフォワード

できるという事は知っていたけど、実際に試したことの無い SSH でのポートフォワードを試してみた。
ポートフォワードの際の中心的なオプション形式は、-L port:host:hostport または -R port:host:hostport っぽい。
前者が、ローカルマシンのポート port への通信を接続先ホスト host のポート hostport にフォワードするというもので、後者が接続先ホストのポート port への通信を任意のホスト Host のポート Hostport にフォワードするもの、なのかな。


ssh -N -f -L 2222:host1:80 user@host1
のように実行すれば、ローカルマシンの2222番ポートへの接続が host1 の80番ポートへとフォワードされる。この時、ローカルマシンは2222番ポートを 127.0.0.1 でのみ LISTEN するが、-g オプションを付与する事により 0.0.0.0 で LISTEN するようになるので、外部ホストからローカルマシンの2222番ポートに接続する事で host1 の80番ポートにアクセスできるようになる、と。
できるという事はわかっていたけど、実際にやってみると簡単なものだなぁ。便利だ。

man ssh より一部抜粋。

-f Requests ssh to go to background just before command execution. This is useful if ssh is going to ask for pass-
words or passphrases, but the user wants it in the background. This implies -n. The recommended way to start
X11 programs at a remote site is with something like ssh -f host xterm.

-g Allows remote hosts to connect to local forwarded ports.

-L port:host:hostport
Specifies that the given port on the local (client) host is to be forwarded to the given host and port on the
remote side. This works by allocating a socket to listen to port on the local side, and whenever a connection
is made to this port, the connection is forwarded over the secure channel, and a connection is made to host port
hostport from the remote machine. Port forwardings can also be specified in the configuration file. Only root
can forward privileged ports. IPv6 addresses can be specified with an alternative syntax: port/host/hostport.

-R port:host:hostport
Specifies that the given port on the remote (server) host is to be forwarded to the given host and port on the
local side. This works by allocating a socket to listen to port on the remote side, and whenever a connection
is made to this port, the connection is forwarded over the secure channel, and a connection is made to host port
hostport from the local machine. Port forwardings can also be specified in the configuration file. Privileged
ports can be forwarded only when logging in as root on the remote machine. IPv6 addresses can be specified with
an alternative syntax: port/host/hostport.

-N Do not execute a remote command. This is useful for just forwarding ports (protocol version 2 only).