标签归档:ssh

SSH反向代理使用心得

有一天想在家里用ssh控制公司的电脑,但是公司的机器处在内网中没有办法直接连上。而我家里的路由器装了Linux系统,而且通过DDNS有独立的域名,这样就可以用ssh反向代理,用公司的电脑ssh反向连接到家里的路由器,然后用家里的电脑ssh到路由器,从而连上公司的电脑。这时家里的路由器相当于是做了个ssh中继。
数据流是:家里电脑->路由器->公司电脑

ssh反向代理简单的来讲,就是用公司电脑在路由器上开了个端口,发送到这个端口的数据都会被转发到公司机器上指定的端口。下面是具体的命令,假设路由器的域名是router.zhoumz.com

ssh -gNfR *:2222:localhost:22 root@router.zhoumz.com

上面的这个命令是在公司电脑上执行的,它表示的含义是:

  • 用root用户登录到router.zhoumz.com
  • 告诉router.zhoumz.com去监听2222端口上来自所有IP的数据
  • 将数据发送到执行此命令机器(公司电脑)上的22端口

参数的含义分别是:

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

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

-f    Requests ssh to go to background just before command execution.

-R    [bind_address:]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 by enclosing
      the address in square brackets.

      By default, the listening socket on the server will be bound to
      the loopback interface only.  This may be overridden by
      specifying a bind_address.  An empty bind_address, or the address
      `*', indicates that the remote socket should listen on all
      interfaces. Specifying a remote bind_address will only succeed
      if the server's GatewayPorts option is enabled (sshd_config(5)).

      If the port argument is `0', the listen port will be dynamically
      allocated on the server and reported to the client at run time.
      When used together with -O forward the allocated port will be
      printed to the standard output.

值得注意的是:想监听来自所有IP的数据,要在远程机器(本例中是路由器)上把GatewayPorts配置项打开 (see sshd_config(5))。

做好上面的步骤之后,回家用电脑ssh路由器的2222端口就可以直接控制公司电脑了。

ssh -p 2222 michael@router.zhoumz.com

这里注意:michael为公司电脑的登录用户名。