SSH隧道技术与端口转发

动态转发(Dynamic Forward)在本地机器上监听一个端口,然后将这个端口的连接通过ssh隧道传输到目标机 本地转发(Local Forward )在本地机器上监听一个端口,然后将这个端口的连接通过ssh隧道传输到指定的目标机的指定端口上 远程转发(Remote Forward )与本地转发正好相反,在远端服务器监听一个端口,所有到远端服务器指定端口的连接都会通过隧道传输到指定目标机的指定端口上 一、动态转发 动态转发通过-D参数指定,ssh -D 7070 myuser@connectToHost意味着,在本地监听7070端口,所有访问本地7070端口的连接都通过与connectToHost建立的ssh隧道转发给目标机(传说中的翻墙) 二、本地转发 本地转发通过-L参数指定,ssh -L sourcePort:forwardToHost:onPort connectToHost意味着:通过与connectToHost建立的ssh连接,转发所有到本地sourcePort端口的连接到forwardToHost的onPort端口,forwardToHost:onPort可以通过connectToHost访问。 英文原文:ssh -L sourcePort:forwardToHost:onPort connectToHost means: connect with ssh to connectToHost, and forward all connection attempts to the local sourcePort to port onPort on the machine called forwardToHost, which can be reached from the connectToHost machine. 如下图一形象的表示了本地转发的过程: ①第一条命令ssh -L 123:localhost:456 remotehost,意味着通过ssh连接到remotehost,然后将连接本地123端口的请求转发到localhost的456端口(因为localhost代表了本地,那remotehost的localhost就是自身) ②第二条命令ssh -L 123:farawayhost:456 remotehost,意味着通过ssh连接到remotehost,然后将连接本地123端口的请求到farawayhost的456端口(因为本地无法访问farawayhost的456端口而remotehost可以访问,通过这种方式,本地可以访问到farawayhost的456端口) 那么本地转发适用于什么样的情况呢: ①第一条命令适用于,我们可以通过ssh访问remote,但无法访问remote的456端口,便可以通过这种方式使用。 ②第二条命令适用于,我们可以通过ssh访问remote ,但无法访问farawayhost的456端口,而remotehost可以,我们就通过这种方式使用。 图一

图一:本地转发

三、远程转发 远程转发通过-R参数指定,ssh -R sourcePort:forwardToHost:onPort connectToHost意味着:通过与connectToHost建立的ssh连接,转发所有到远程sourcePort端口的连接到forwardToHost的onPort端口,forwardToHost:onPort可以通过本地访问。 英文原文: ssh -R sourcePort:forwardToHost:onPort connectToHost means: connect with ssh to connectToHost, and forward all connection attempts to the remote sourcePort to port onPort on the machine called forwardToHost, which can be reached from your local machine. 如下图二形象的表示了远程转发的过程: ①第一条命令ssh -R 123:localhost:456 remotehost,意味着通过连接到remotehost的ssh隧道,然后将连接远程123端口的请求转发到localhost的456端口(因为localhost代表了本地,那本地的localhost就是自身) ②第二条命令ssh -L 123:nearhost:456 remotehost,意味着通过连接到remotehost的ssh隧道,然后将所有连接远程123端口的请求转发到nearhost的456端口。 那么远程转发适用于什么样的情况呢: ①第一条命令适用于,我们可以通过ssh访问remote,但本地的456端口remote无法访问,便可以通过这种方式使用。 ②第二条命令适用于,我们可以通过ssh访问remote ,也可以访问nearhost的456端口,但remote无法访问nearhost的456端口,我们就通过这种方式使用。(传说中的内网渗透) 图二

图二:远程转发

  四、SSH的其它参数 -N 不执行脚本或命令,通常与-f连用 -f 后台认证用户/密码,通常和-N连用,不用登录到远程主机 -C 压缩数据传输 -T 不为这个连接分配TTY,与-N配合使用表示只传输数据不执行命令 参考:http://unix.stackexchange.com/questions/46235/how-does-reverse-ssh-tunneling-work 参考:http://www.ruanyifeng.com/blog/2011/12/ssh\_port\_forwarding.html 参考:http://linuxcommand.org/man_pages/ssh1.html