2010年9月27日

SSH 端口转发

再说如何使用SSH端口转发前,我们先看看它的作用

如上图,主机A1和主机B1可以互相访问,A1,A2可以互相访问;B1,B2可以互相访问。其它主机之间不能直接访问。
SSH端口转发的神奇之处在于:我们我们可以让A2访问网络B的主机B1和B2;让B2访问A1和A2。有如下3个ssh端口转发方法可以达到这个目的
  • ssh -C -f -N -g -L listen_port:DST_Host:DST_port user@Tunnel_Host

    • 在ssh客户端(本地)监听端口(listen_port),此端口的访问被转到DST_Host的DST_port
    • ssh服务端(Tunnel_Host)必须能成常访问DST_Host:DST_port
    • 应用举例:(以下操作均在本地机器上执行,本地机器的ip为1.1.1.34,这是在局域网内手动指定的一个ip)



        aray:~# ifconfig eth0
        eth0      Link encap:Ethernet  HWaddr 00:25:b3:74:b6:eb  
                  inet addr:1.1.1.34  Bcast:1.1.1.255  Mask:255.255.255.0
                  inet6 addr: fe80::225:b3ff:fe74:b6eb/64 Scope:Link
                  UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
                  RX packets:134567 errors:0 dropped:0 overruns:0 frame:0
                  TX packets:70777 errors:0 dropped:0 overruns:0 carrier:0
                  collisions:0 txqueuelen:1000 
                  RX bytes:173447487 (165.4 MiB)  TX bytes:5818516 (5.5 MiB)
                  Interrupt:17 
        
        aray@aray:~$ ssh -C -f -N -g -L 9999:192.168.1.1:80 araycn.3322.org
        Warning: Permanently added the RSA host key for IP address '222.182.90.241' to the list of known hosts.
        aray@araycn.3322.org's password: 
        bind: Address already in use
        
        aray@aray:~$ ssh -C -f -N -g -L 1.1.1.34:9998:192.168.1.1:80 araycn.3322.org
        aray@araycn.3322.org's password: 
        
        aray@aray:~$ netstat -nap | grep ssh | grep tcp
        (Not all processes could be identified, non-owned process info
         will not be shown, you would have to be root to see it all.)
        tcp        0      0 1.1.1.34:9998           0.0.0.0:*               LISTEN      4367/ssh        
        tcp        0      0 1.1.1.34:32903          222.182.90.241:22       ESTABLISHED 4352/ssh        
        tcp        0      0 1.1.1.34:34268          222.182.90.241:22       ESTABLISHED 4367/ssh        
        tcp6       0      0 :::9999                 :::*                    LISTEN      4352/ssh   
        
        注意: ssh -C -f -N -g -L 1.1.1.34:9998:192.168.1.1:80 araycn.3322.org 这个指定本地只监听1.1.1.34这个ip,如果不指定1.1.1.34,则监听所有网络连接。
        现在本地机器(1.1.1.34)所在的局域网内的所有机器,都可以访问http://1.1.1.34:9998或者http://1.1.1.34:9999,来打开远程局域网里的网页http://192.168.1.1了
  • ssh -C -f -N -g -R listen_port:DST_Host:DST_port user@Tunnel_Host

    • 在远ssh服务端(Tunnel_Host)上,监听端口(listen_port),访问远程服务器的端口listen_port,就等于访问了本地机器访问得到的DST_Host的端口DST_Port)
  • ssh -C -f -N -g -D listen_port user@Tunnel_Host

    • 在ssh客户端建立一个SOCKETS4代理服务器,这个代理服务器监听本地的listen_port,通过这个代理服务器,能访问到Tunnel_Host访问得到的仍和服务器。

没有评论:

发表评论