Secure Shell (SSH)

本章记录了自己在使用SSH的过程中遇到的一些问题,及其解决方法。

通过ssh建立安全隧道(ssh tunnelling,也称端口映射,Port Forwarding)

通过ssh的端口映射功能可以方便地存取一下无法直接访问的资源。又分为本地映射(Local Forward)和远程映射(Remote Forward)。

  • 本地映射(Local Forward):

    $ ssh -f -g -A -X -N -T -L 1234:remote-host2:5678 user@remote-host

    或者通过修改ssh的配置文件:

    $ cat ~/.ssh/config
    Host remote-host
         Hostname x.x.x.x (your remote host IP)
         LocalForward 1234:remote-host2:5678
         User user
    $ ssh user@remote-host

    所有对本地1234端口的访问都通过remote-host被转发到remote-host2的5678端口。有些DMZ中只开放sshd的22端口,通过本地映射,你可以访问远程计算机上的所有服务。

  • 远程映射(Remote Forward):

    $ ssh -f -g -A -X -N -T -R 1234:remote-host2:5678 user@remote-host

    或者通过修改ssh的配置文件:

    $ cat ~/.ssh/config
    Host remote-host
         Hostname x.x.x.x (your remote host IP)
         RemoteForward 1234:remote-host2:5678
         User user
    $ ssh user@remote-host

    所有对remote-host的1234端口的访问都通过本机被转发到remote-host2的5678端口。通过远程映射,你可以通过家中的机子(有公网IP,可以ssh登录)来访问公司防火墙内部的计算机。

SSH Web Proxy

Create local dynamic application-level port forwarding:

$ ssh -qTfnN -D localhost:8888 user@remote-host

Setup browser to use localhost:8888 as socks 5 proxy.

公钥认证

使用公钥认证经常遇到的问题就是一些文件的权限问题。一些问题可以通过查看/var/log/secure来发现。

要配置两台计算机使用公钥认证,可以通过分别在两台机子host1、host2上运行如下脚本:

$ ssh-keygen -t rsa -b 1024 # don't input any password
$ ssh $host1 cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
$ ssh $host2 cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
$ chmod 600 ~/.ssh/authorized_keys # important!

配置ssh使用代理服务器,穿越企业防火墙

下载 connect.c ,编译,拷贝到系统`/usr/bin`目录:

$ gcc connect.c -o connect
$ sudo cp connect /usr/bin

编辑ssh的配置文件`~/.ssh/config`,增加:

$ cat ~/.ssh/config
Host remote-host
     ProxyCommand connect -H your.proxy.com:port %h %p
$ ssh user@remote-host

加快SSH连接速度方法

SSH登录时会进行DNS反查,如果你的DNS Server速度比较慢,会发生等待。知道了原因解决方法就出来了:就是提高域名解析的速度。可以将主机名写到/etc/hosts中来解决。

使用expect实现ssh自动交互

参考使用expect实现的自动远端命令执行的脚本 remote-exec .

SSH保持连接(Keep Alive)

可以使用下面的方法之一:

  • 增加下面的内容到~/.ssh/config或者/etc/ssh/ssh_config:

    Host *

    ServerAliveInterval 60 # in second

  • 执行下面的脚本:

    while date; do sleep 10; done

    当要输入命令时,只需要按下ctrl-c.

SSH (last edited 2010-05-03 07:13:37 by ZhigangWang)