Total Pageviews

Friday 1 April 2016

SSH tunnel tips

从我两三年前接触 SSH 的时候我就在文档上见过 SSH tunnel 相关的东西,然而当时没有怎么看明白,也就一直没有深究,直到最近需求越来越多了,才终于发现这个东西原来这么有用,于是记录在此。

SSH tunnel 主要有三种,一种是 dynamic application-level port forwarding ,可以用来作为 SOCKS proxy ,通常翻墙就是用的这种端口映射;一种是 Local Forwarding ,主要用于提供常规的加密隧道,例如让 IMAP 协议通过这个加密隧道,避免密码在网络上被人监听到;一种是 Remote Forwarding ,可以用于逆向穿透 NAT 。其实,另外还有一种专门为 X 打造的 X11 Forwarding ,一般不会用到,Linux 下远程登录通常不会需要开启 X 程序,或者有其他更好用的方法,因此我们这里并不打算介绍这个。

首先我们来假定一个网络环境:有一个防火墙,在防火墙内部有一个机器 H ,通过 NAT 访问 Internet ,并且在防火墙外的 Internet 上的机器 T 上有一个 ssh 帐号,而另一台 Internet 上的机器 S 则是一台公共服务器,例如 Google 的服务器。如下图所示:
ssh
首先来说 Local Forwarding ,相关的文档上都用的是阅读邮件这个经典的例子:用户在 T 上有一个 IMAP 服务器,本来他可以直接连接到 T:143 上阅读邮件的,但是这是未加密连接,如果你的 IMAP 服务器是用明文密码验证的方式的话,就很糟糕了,这样你的密码很容易被别人窃听到。这个时候 SSH 隧道就出来了,通过如下命令可以建立一个 SSH 隧道:

ssh -L 9143:localhost:143 T
首先不看参数,这个命令是发起一个 ssh 连接到主机 T ,然后选项 -L 表示 Local Forwarding ,9143 表示本地(亦即 H)的端口,然后 localhost:143 则是远程(即 T)上所对应的主机和端口。这样一来,你在 H 上连接端口 9143 ,就相当于你在 T 上连接 localhost:143 一样,SSH 建立的隧道会帮你在两个主机间传递信息。现在只要配置 H 上的邮件客户端去连接 localhost:9143 ,就能通过加密的方式访问到 T 上的 localhost:143 这个邮件服务器了。注意两个主机上的 localhost 的区别。

当然隧道并不限于 localhost ,如果你愿意,可以做这样一个映射:

ssh -L 9999:www.google.com:80 T
这样,你可以在 H 的浏览器里输入 localhost:9999 访问到 Google 了。注意到 H 和 T 之间的数据传输是加密的,所以,如果 H 是处在伟大的局域网内,而 T 是在外部的话,可以通过这样的方法来访问 Google 而不受防火墙的限制。不过这种方法每个端口只能映射一个网站,很不方便。要用作代理通常还是使用 dynamic application-level port forwarding 的方式,如下:

ssh -D 9999 T
这样建立起来的隧道实际上是一个 SOCKS 代理,当然要使用 SOCKS 代理需要客户端能够支持才行,比如在 Firefox 中,只要在代理处填写 localhost:9999 并勾选 SOCKS5 代理即可。另外,还可以使用诸如 ProxyChains 之类的程序让本身不支持 SOCKS 代理的程序能够“透明地”使用 SOCKS 代理,不过我并没有尝试过,不知道稳定性如何。

最后要介绍的就是 Remote Forwarding 了,首先看命令吧:

ssh -R 9923:10.13.21.88:23 T
这里 10.13.21.88 是 H 所在的局域网里的一台主机,23 是 telnet 默认的端口,其实这就是浙大飘渺水云间 bbs (亦即“88”)的校内地址了,由于是在局域网内,Internet 上的 T 是访问不到它的,现在 H 建立了一个到 T 的 Remote Forwarding ,对应之前的 Local Forwarding 的意思,应该能猜到了吧?现在在 T 上可以通过访问 localhost:9923 来上 88 了。 :D 换句话说,在 T 上访问 localhost:9923 相当于在 H 上访问 10.13.21.88:23 ,这成了一个反向的隧道。

另外,上面三种 Forwarding 默认建立的 socket 都是监听本机的 loopback 地址的,这样外面的机器是不能访问这个端口映射的。对于最后那个飘渺水云间的隧道来讲,默认情况下,T 虽然可以通过 localhost:9923 来上 88 ,但是 S 却不能通过 T:9923 来访问到,而是会得到一个 Connection Refused 的错误,这样做也是为了安全起见,不过,如果确实想要让这个隧道可以从其他主机访问到的话,上面三个命令都可以在映射参数前面再加一个地址参数。例如飘渺 水云间的那个映射其实等价于:

ssh -R localhost:9923:10.13.21.88:23 T
把 localhost 改成 * 就可以让其他机器也访问到了(注意加上引号以防止 shell 把星号给展开了):

ssh -R '*:9923:10.13.21.88:23' T
唔,还有一点要说明的是,对于 -L 和 -D 来说,都是这样就可以了,而 -R 则还需要远程的 sshd 配置一下 GatewayPorts 选项,默认情况下是 no ,这样会无视掉客户端的请求,强制 bind 到 loopback 地址上,而 yes 则相当于强制 * ,如果设置成 clientspecified 则允许客户端来选择。因此在 /etc/ssh/sshd_config 文件里添加这样一行:

GatewayPorts clientspecified
再重启 ssh 服务即可。虽然学校提供了 RVPN 可以从校外访问到校内的资源,但是并没有提供 Linux 下的解决方案。在没有校外独立 IP 的情况下用这样的方法在外面访问学校的资源就变得非常有用了。要是 -D 也能有一个对应的 Reverse 的方案也许会更方便一些,不过也许可以用 -R 和 -D 桥接一个:

H$ ssh -D 9999 localhost
H$ ssh -R 9999:localhost:9999 T
在 T 上使用 localhost:9999 作为 SOCKS 代理,而该端口的数据会被 forward 到 H 上的 localhost:9999 ,那里是实际的 SOCKS 代理服务器。不过我没有实际测试过是不是真的可以用。 :p

最后再说一句,FTP 是另一个经典的明文传输密码的协议,但是它却没法通过 SSH 隧道使用,因为它需要另外打开一个 socket 来传输数据,这时就不在 SSH 的接管范围之内了,我想这也许是 SFTP 这个东西诞生的直接原因吧。其实使用了 -R 的端口映射之后,要 scp 回来是一件很容易的事,例如:

H$ ssh -R 9922:localhost:22 T
T$ scp foo.txt -P 9922 localhost:~/
可以将 T 上的 foo.txt 拷贝回 H 的主目录中。当然,如果只是为了做一个端口映射,可不必打开一个远程 shell ,只要再为 ssh 加上 -Nf 参数即可,具体是什么意思自己 man 吧。它会在后台运行,一直等待到对应隧道端口的连接。需要注意的是,在有了第一个连接之后,如果连接数降为零了,它会自动退出。所以我通常还是会打开远程 shell ,不过使用 screen 把它放在后台去,就不会妨碍了,需要的时候可以调出来,也可以方便地控制它什么时候退出。 :)

最后,在客户端的 ~/.ssh/config 里加入

ServerAliveInterval 180
这样可以防止长时间的 idle 导致 ssh 连接被自动断开。

from: http://blog.pluskid.org/?p=369
------------

linux下也可以使用plink.exe

ubuntu/debian用户可以直接安装:

   
sudo apt-get install putty

安装完成后执行

   
plink -N -D 127.0.0.1:1080 -pw 密码 USERNAME@SSH服务器地址

-------------------------------------------------------

我以前以为 ssh 只能登录主机执行命令,ssh 教我它还会 scp;

我以为会 scp 很厉害了,ssh 教我它还会 sftp;

我以为会 sftp 了不得了,ssh 教我它还会 sshfs;

我以为会 sshfs 已经相当牛了,ssh 教我它还能把服务器端口绑定到本机端口(ssh -L);

我以为把服务器端口绑定到本机端口就已经上天了,ssh 教我它还能把本机端口绑定到服务器端口(ssh -R)...

然后,我怨念已久的共享上网终于实现了!

PS: 用软件还得选老牌开源软件,openssh 那么多年没更新了,在 Windows 下用 cygwin 运行都比 freesshd 稳定,不得不赞一个。Win 下的一些软件,窗口搞得花里胡哨的,功能和稳定性却不知道放到第几位了,跟人一样,长得好看的未必靠谱。

----------------------------------------------------------------------------------------------------------
实战 SSH 端口转发

    通过本文的介绍,读者可以从中了解到如何应用 SSH 端口转发机制来解决日常工作 / 生活中的一些问题。学会在非安全环境下使用端口转发来加密网络应用,保护个人隐私以及重要商业信息。同时也能够用此技术解决工作中一些常见问题,例如解决 防火墙及网络应用本身带来的一些限制。

第一部分 概述

当你在咖啡馆享受免费 WiFi 的时候,有没有想到可能有人正在窃取你的密码及隐私信息?当你发现实验室的防火墙阻止了你的网络应用端口,是不是有苦难言?来看看 SSH 的端口转发功能能给我们带来什么好处吧!

端口转发概述

让 我们先来了解一下端口转发的概念吧。我们知道,SSH 会自动加密和解密所有 SSH 客户端与服务端之间的网络数据。但是,SSH 还同时提供了一个非常有用的功能,这就是端口转发。它能够将其他 TCP 端口的网络数据通过 SSH 链接来转发,并且自动提供了相应的加密及解密服务。这一过程有时也被叫做“隧道”(tunneling),这是因为 SSH 为其他 TCP 链接提供了一个安全的通道来进行传输而得名。例如,Telnet,SMTP,LDAP 这些 TCP 应用均能够从中得益,避免了用户名,密码以及隐私信息的明文传输。而与此同时,如果您工作环境中的防火墙限制了一些网络端口的使用,但是允许 SSH 的连接,那么也是能够通过将 TCP 端口转发来使用 SSH 进行通讯。总的来说 SSH 端口转发能够提供两大功能:

    加密 SSH Client 端至 SSH Server 端之间的通讯数据。
    突破防火墙的限制完成一些之前无法建立的 TCP 连接。


图 1. SSH 端口转发
SSH 端口转发

如上图所示,使用了端口转发之后,TCP 端口 A 与 B 之间现在并不直接通讯,而是转发到了 SSH 客户端及服务端来通讯,从而自动实现了数据加密并同时绕过了防火墙的限制。




    回页首



第二部分 本地转发与远程转发

本地转发实例分析

我 们先来看第一个例子,在实验室里有一台 LDAP 服务器(LdapServerHost),但是限制了只有本机上部署的应用才能直接连接此 LDAP 服务器。如果我们由于调试或者测试的需要想临时从远程机器(LdapClientHost)直接连接到这个 LDAP 服务器 , 有什么方法能够实现呢?

答案无疑是本地端口转发了,它的命令格式是:

ssh -L <local port>:<remote host>:<remote port> <SSH hostname>



在 LdapClientHost 上执行如下命令即可建立一个 SSH 的本地端口转发,例如:

$ ssh -L 7001:localhost:389 LdapServerHost



图 2. 本地端口转发
本地端口转发

这里需要注意的是本例中我们选择了 7001 端口作为本地的监听端口,在选择端口号时要注意非管理员帐号是无权绑定 1-1023 端口的,所以一般是选用一个 1024-65535 之间的并且尚未使用的端口号即可。

然后我们可以将远程机器(LdapClientHost)上的应用直接配置到本机的 7001 端口上(而不是 LDAP 服务器的 389 端口上)。之后的数据流将会是下面这个样子:

    我们在 LdapClientHost 上的应用将数据发送到本机的 7001 端口上,
    而本机的 SSH Client 会将 7001 端口收到的数据加密并转发到 LdapServertHost 的 SSH Server 上。
    SSH Server 会解密收到的数据并将之转发到监听的 LDAP 389 端口上,
    最后再将从 LDAP 返回的数据原路返回以完成整个流程。

我们可以看到,这整个流程应用并没有直接连接 LDAP 服务器,而是连接到了本地的一个监听端口,但是 SSH 端口转发完成了剩下的所有事情,加密,转发,解密,通讯。

这里有几个地方需要注意:

    SSH 端口转发是通过 SSH 连接建立起来的,我们必须保持这个 SSH 连接以使端口转发保持生效。一旦关闭了此连接,相应的端口转发也会随之关闭。
    我们只能在建立 SSH 连接的同时创建端口转发,而不能给一个已经存在的 SSH 连接增加端口转发。
    你 可能会疑惑上面命令中的 <remote host> 为什么用 localhost,它指向的是哪台机器呢?在本例中,它指向 LdapServertHost 。我们为什么用 localhost 而不是 IP 地址或者主机名呢?其实这个取决于我们之前是如何限制 LDAP 只有本机才能访问。如果只允许 lookback 接口访问的话,那么自然就只有 localhost 或者 IP 为 127.0.0.1 才能访问了,而不能用真实 IP 或者主机名。
    命令中的 <remote host> 和 <SSH hostname> 必须是同一台机器么?其实是不一定的,它们可以是两台不同的机器。我们在后面的例子里会详细阐述这点。
    好了,我们已经在 LdapClientHost 建立了端口转发,那么这个端口转发可以被其他机器使用么?比如能否新增加一台 LdapClientHost2 来直接连接 LdapClientHost 的 7001 端口?答案是不行的,在主流 SSH 实现中,本地端口转发绑定的是 lookback 接口,这意味着只有 localhost 或者 127.0.0.1 才能使用本机的端口转发 , 其他机器发起的连接只会得到“ connection refused. ”。好在 SSH 同时提供了 GatewayPorts 关键字,我们可以通过指定它与其他机器共享这个本地端口转发。
    ssh -g -L <local port>:<remote host>:<remote port> <SSH hostname>

远程转发实例分析

我们来看第二个例子,这次假设由于网络或防火墙的原因我们不能用 SSH 直接从 LdapClientHost 连接到 LDAP 服务器(LdapServertHost),但是反向连接却是被允许的。那此时我们的选择自然就是远程端口转发了。

它的命令格式是:

ssh -R <local port>:<remote host>:<remote port> <SSH hostname>



例如在 LDAP 服务器(LdapServertHost)端执行如下命令:

$ ssh -R 7001:localhost:389 LdapClientHost



图 3. 远程端口转发
远程端口转发

和 本地端口转发相比,这次的图里,SSH Server 和 SSH Client 的位置对调了一下,但是数据流依然是一样的。我们在 LdapClientHost 上的应用将数据发送到本机的 7001 端口上,而本机的 SSH Server 会将 7001 端口收到的数据加密并转发到 LdapServertHost 的 SSH Client 上。 SSH Client 会解密收到的数据并将之转发到监听的 LDAP 389 端口上,最后再将从 LDAP 返回的数据原路返回以完成整个流程。

看到这里,你是不是会有点糊涂了么?为什么叫本地转发,而有时又叫远程转发?这两者有什么区别?

本地转发与远程转发的对比与分析

不 错,SSH Server,SSH Client,LdapServertHost,LdapClientHost,本地转发,远程转发,这么多的名词的确容易让人糊涂。让我们来分析一下其 中的结构吧。首先,SSH 端口转发自然需要 SSH 连接,而 SSH 连接是有方向的,从 SSH Client 到 SSH Server 。而我们的应用也是有方向的,比如需要连接 LDAP Server 时,LDAP Server 自然就是 Server 端,我们应用连接的方向也是从应用的 Client 端连接到应用的 Server 端。如果这两个连接的方向一致,那我们就说它是本地转发。而如果两个方向不一致,我们就说它是远程转发。

我们可以回忆上面的两个例子来做个对照。

本地转发时:

LdapClientHost 同时是应用的客户端,也是 SSH Client,这两个连接都从它指向 LdapServertHost(既是 LDAP 服务端,也是 SSH Server)。

远程转发时:

LdapClientHost 是应用的客户端,但却是 SSH Server ;而 LdapServertHost 是 LDAP 的服务端,但却是 SSH Client 。这样两个连接的方向刚好相反。

另 一个方便记忆的方法是,Server 端的端口都是预定义的固定端口(SSH Server 的端口 22,LDAP 的端口 389),而 Client 端的端口都是动态可供我们选择的端口(如上述例子中选用的 7001 端口)。如果 Server 端的两个端口都在同一台机器,Client 端的两个端口都在另一台机器上,那么这就是本地连接;如果这四个端口交叉分布在两个机器上,每台机器各有一个 Server 端端口,一个 Client 端端口,那就是远程连接。

弄清楚了两者的区别之后,再来看看两者的相同之处。如果你所在的环境下,既允许 LdapClientHost 发起 SSH 连接到 LdapServerHost,也允许 LdapServerHost 发起 SSH 连接到 LdapClientHost 。那么这时我们选择本地转发或远程转发都是可以的,能完成一样的功能。

接着让我们来看个进阶版的端口转发。我们之前涉及到的各种连接 / 转发都只涉及到了两台机器,还记得我们在本地转发中提到的一个问题么?本地转发命令中的 <remote host> 和 <SSH hostname> 可以是不同的机器么?

ssh -L <local port>:<remote host>:<remote port> <SSH hostname>



答案是可以的!让我们来看一个涉及到四台机器 (A,B,C,D) 的例子。


图 4. 多主机转发应用
多主机转发应用

在 SSH Client(C) 执行下列命令来建立 SSH 连接以及端口转发:

$ ssh -g -L 7001:<B>:389 <D>



然 后在我们的应用客户端(A)上配置连接机器(C )的 7001 端口即可。注意我们在命令中指定了“ -g ”参数以保证机器(A)能够使用机器(C)建立的本地端口转发。而另一个值得注意的地方是,在上述连接中,(A)<-> (C) 以及 (B)<->(D) 之间的连接并不是安全连接,它们之间没有经过 SSH 的加密及解密。如果他们之间的网络并不是值得信赖的网络连接,我们就需要谨慎使用这种连接方式了。




    回页首



第三部分 其他类型的转发

动态转发实例分析

恩, 动态转发,听上去很酷。当你看到这里时,有没有想过我们已经讨论过了本地转发,远程转发,但是前提都是要求有一个固定的应用服务端的端口号,例如前面例子 中的 LDAP 服务端的 389 端口。那如果没有这个端口号怎么办?等等,什么样的应用会没有这个端口号呢?嗯,比如说用浏览器进行 Web 浏览,比如说 MSN 等等。

当我们在一个不安全的 WiFi 环境下上网,用 SSH 动态转发来保护我们的网页浏览及 MSN 信息无疑是十分必要的。让我们先来看一下动态转发的命令格式:

$ ssh -D <local port> <SSH Server>



例如:

$ ssh -D 7001 <SSH Server>



图 5. 动态端口转发
动态端口转发

似乎很简单,我们依然选择了 7001 作为本地的端口号,其实在这里 SSH 是创建了一个 SOCKS 代理服务。来看看帮助文档中对 -D 参数的描述:

-D port
 This works by allocating a socket to listen to port on the local
 side, and whenever a connection is made to this port, the con-
 nection is forwarded over the secure channel, and the applica-
 tion protocol is then used to determine where to connect to from
 the remote machine.  Currently the SOCKS4 and SOCKS5 protocols
 are supported, and ssh will act as a SOCKS server.  Only root
 can forward privileged ports.  Dynamic port forwardings can also
 be specified in the configuration file.



之 后的使用就简单了,我们可以直接使用 localhost:7001 来作为正常的 SOCKS 代理来使用,直接在浏览器或 MSN 上设置即可。在 SSH Client 端无法访问的网站现在也都可以正常浏览。而这里需要值得注意的是,此时 SSH 所包护的范围只包括从浏览器端(SSH Client 端)到 SSH Server 端的连接,并不包含从 SSH Server 端 到目标网站的连接。如果后半截连接的安全不能得到充分的保证的话,这种方式仍不是合适的解决方案。

X 协议转发实例分析

好了,让我们来看最后一个例子 - X 协议转发。

我 们日常工作当中,可能会经常会远程登录到 Linux/Unix/Solaris/HP 等机器上去做一些开发或者维护,也经常需要以 GUI 方式运行一些程序,比如要求图形化界面来安装 DB2/WebSphere 等等。这时候通常有两种选择来实现:VNC 或者 X 窗口,让我们来看看后者。

使用 X 窗口通常需要分别安装:X Client 和 X Server 。在本例中我们的 X Client 就是所访问的远程 Linux/Unix/Solaris/HP,而我们的 X Server 则是发起访问的本地机器(例如你面前正在使用的笔记本或台式机)。把 X Client 端的 X 窗口显示在 X Server 端需要先行在 X Client 端指定 X Server 的位置,命令格式如下:

export DISPLAY=<X Server IP>:<display #>.<virtual #>



例如:

export DISPLAY=myDesktop:1.0



然后直接运行 X 应用即可,X 窗口就会自动在我们的本地端打开。

一 切运行正常,但是,这时候 IT 部门突然在远程 Linux/Unix/Solaris/HP 前面加了一道防火墙。非常不幸的是,X 协议并不在允许通过的列表之内。怎么办?只能使用 VNC 了么?不,其实只要使用了 SSH 端口转发即可通过,同时也对 X 通讯数据做了加密,真是一举两得。(当然,使用此方法前最好先咨询相关 IT 部门是否符合相应的安全条例,以免造成违规操作。)

建立命令也很简单,直接从本地机器(X Server 端)发起一个如下的 SSH 连接即可:

$ ssh -X <SSH Server>



图 5. X 转发
X 转发

建立连接之后就可以直接运行远程的 X 应用。注意建立 X 转发之后会自动设置 DISPLAY 环境变量,通常会被设置成localhost:10.0,我们无需也不应该在连接之后再进行修改此环境变量。

一个比较常见的场景是,我们的本地机器是 Windows 操作系统,这时可以选择开源的 XMing 来作为我们的 XServer,而 SSH Client 则可以任意选择了,例如 PuTTY,Cygwin 均可以配置 访问 SSH 的同时建立 X 转发。




    回页首



第四部分 总结

至 此,我们已经完成了本地端口转发,远程端口转发,动态端口转发以及 X 转发的介绍。回顾起来,总的思路是通过将 TCP 连接转发到 SSH 通道上以解决数据加密以及突破防火墙的种种限制。对一些已知端口号的应用,例如 Telnet/LDAP/SMTP,我们可以使用本地端口转发或者远程端口转发来达到目的。动态端口转发则可以实现 SOCKS 代理从而加密以及突破防火墙对 Web 浏览的限制。对于 X 应用,无疑是 X 转发最为适用了。虽然每一部分我们都只是简单的介绍了一下,但如果能灵活应用这些技巧,相信对我们的日常生活 / 工作也是会有所帮助的。

from: https://www.ibm.com/developerworks/cn/linux/l-cn-sshforward/

参考资料

《 SSH 权威指南》(O'Reilly 图书)详细介绍了 SSH 相关的更多技术内幕及相关技巧。

www.openssh.org

-------------------------------------------------------------------------
关于ssh 配置文件的参数说明

SSH的密匙的配置方法,相信安全,加密的数据传输方式也是你想要的!学习一下吧
SSH使用指南
介绍SSH
什么是SSH?
传统的网络服务程序,如:ftp、pop和telnet在本质上都是不安全的,因为它们在网络上用明文传送口令和数据,别有用心的人非常容易就可以截获 这些口令和数据。而且,这些服务程序的安全验证方式也是有其弱点的,就是很容易受到“中间人”(man-in-the-middle)这种方式的攻击。所 谓 “中间人”的攻击方式,就是“中间人”冒充真正的服务器接收你的传给服务器的数据,然后再冒充你把数据传给真正的服务器。服务器和你之间的数据传送被“中 间人”一转手做了手脚之后,就会出现很严重的问题。
SSH的英文全称是Secure SHell。通过使用SSH,你可以把所有传输的数据进行加密,这样“中间人”这种攻击方式就不可能实现了,而且也能够防止DNS和IP欺骗。还有一个额 外的好处就是传输的数据是经过压缩的,所以可以加快传输的速度。SSH有很多功能,它既可以代替telnet,又可以为ftp、pop、甚至ppp提供一 个安全的“通道”。
最初SSH是由芬兰的一家公司开发的。但是因为受版权和加密算法的限制,现在很多人都转而使用OpenSSH。OpenSSH是SSH的替代软件,而且是免费的,可以预计将来会有越来越多的人使用它而不是SSH。
SSH是由客户端和服务端的软件组成的,有两个不兼容的版本分别是:1.x和2.x。用SSH 2.x的客户程序是不能连接到SSH 1.x的服务程序上去的。OpenSSH 2.x同时支持SSH 1.x和2.x。
SSH的安全验证是如何工作的
从客户端来看,SSH提供两种级别的安全验证。
第一种级别(基于口令的安全验证)只要你知道自己帐号和口令,就可以登录到远程主机。所有传输的数据都会被加密,但是不能保证你正在连接的服务器就是你想连接的服务器。可能会有别的服务器在冒充真正的服务器,也就是受到“中间人”这种方式的攻击。
第二种级别(基于密匙的安全验证)需要依靠密匙,也就是你必须为自己创建一对密匙,并把公用密匙放在需要访问的服务器上。如果你要连接到SSH服务器 上,客户端软件就会向服务器发出请求,请求用你的密匙进行安全验证。服务器收到请求之后,先在你在该服务器的家目录下寻找你的公用密匙,然后把它和你发送 过来的公用密匙进行比较。如果两个密匙一致,服务器就用公用密匙加密“质询”(challenge)并把它发送给客户端软件。客户端软件收到“质询”之后 就可以用你的私人密匙解密再把它发送给服务器。
用这种方式,你必须知道自己密匙的口令。但是,与第一种级别相比,第二种级别不需要在网络上传送口令。
第二种级别不仅加密所有传送的数据,而且“中间人”这种攻击方式也是不可能的(因为他没有你的私人密匙)。但是整个登录的过程可能需要10秒。
安装并测试OpenSSH
因为受到美国法律的限制,在很多Linux的发行版中都没有包括OpenSSH。但是,可以从网络上下载并安装OpenSSH(有关OpenSSH的安 装和配置请参考:http://www.linuxaid.com.cn/engineer/brimmer/html/OpenSSH.htm)。
安装完OpenSSH之后,用下面命令测试一下:
ssh -l [your accountname on the remote host] [address of the remote host]
如果OpenSSH工作正常,你会看到下面的提示信息:
The authenticity of host [hostname] can't be established.
Key fingerprint is 1024 5f:a0:0b:65:d3:82:df:ab:44:62:6d:98:9c:fe:e9:52.
Are you sure you want to continue connecting (yes/no)?
OpenSSH告诉你它不知道这台主机,但是你不用担心这个问题,因为你是第一次登录这台主机。键入“yes”。这将把这台主机的“识别标记”加到“~/.ssh/know_hosts”文件中。第二次访问这台主机的时候就不会再显示这条提示信息了。
然后,SSH提示你输入远程主机上你的帐号的口令。输入完口令之后,就建立了SSH连接,这之后就可以象使用telnet那样使用SSH了。
SSH的密匙
生成你自己的密匙对
生成并分发你自己的密匙有两个好处:
1) 可以防止“中间人”这种攻击方式
2) 可以只用一个口令就登录到所有你想登录的服务器上
用下面的命令可以生成密匙:
ssh-keygen
如果远程主机使用的是SSH 2.x就要用这个命令:
ssh-keygen –d
在同一台主机上同时有SSH1和SSH2的密匙是没有问题的,因为密匙是存成不同的文件的。
ssh-keygen命令运行之后会显示下面的信息:
Generating RSA keys: ............................ooooooO......ooooooO
Key generation complete.
Enter file in which to save the key (/home/[user]/.ssh/identity):
[按下ENTER就行了]
Created directory '/home/[user]/.ssh'.
Enter passphrase (empty for no passphrase):
[输入的口令不会显示在屏幕上]
Enter same passphrase again:
[重新输入一遍口令,如果忘记了口令就只能重新生成一次密匙了]
Your identification has been saved in /home/[user]/.ssh/identity.
[这是你的私人密匙]
Your public key has been saved in /home/[user]/.ssh/identity.pub.
The key fingerprint is: 2a:dc:71:2f:27:84:a2:e4:a1:1e:a9:63:e2:fa:a5:89 [user]@[local machine]
“ssh-keygen –d”做的是几乎同样的事,但是把一对密匙存为(默认情况下)“/home/[user]/.ssh/id_dsa”(私人密匙)和“/home/[user]/.ssh/id_dsa.pub”(公用密匙)。
现在你有一对密匙了:公用密匙要分发到所有你想用ssh登录的远程主机上去;私人密匙要好好地保管防止别人知道你的私人密匙。用“ls –l ~/.ssh/identity”或“ls –l ~/.ssh/id_dsa”所显示的文件的访问权限必须是“-rw-------”。
如果你怀疑自己的密匙已经被别人知道了,不要迟疑马上生成一对新的密匙。当然,你还要重新分发一次公用密匙。
分发公用密匙
在每一个你需要用SSH连接的远程服务器上,你要在自己的家目录下创建一个“.ssh”的子目录,把你的公用密匙“identity.pub” 拷贝到这个目录下并把它重命名为“authorized_keys”。然后执行:
chmod 644 .ssh/authorized_keys
这一步是必不可少的。如果除了你之外别人对“authorized_keys”文件也有写的权限,SSH就不会工作。
如果你想从不同的计算机登录到远程主机,“authorized_keys”文件也可以有多个公用密匙。在这种情况下,必须在新的计算机上重新生成一对 密匙,然后把生成的“identify.pub”文件拷贝并粘贴到远程主机的“authorized_keys”文件里。当然在新的计算机上你必须有一个 帐号,而且密匙是用口令保护的。有一点很重要,就是当你取消了这个帐号之后,别忘了把这一对密匙删掉。
配置SSH
配置客户端的软件
OpenSSH有三种配置方式:命令行参数、用户配置文件和系统级的配置文件(“/etc/ssh/ssh_config”)。命令行参数优先于配置文 件,用户配置文件优先于系统配置文件。所有的命令行的参数都能在配置文件中设置。因为在安装的时候没有默认的用户配置文件,所以要把 “/etc/ssh/ssh_config”拷贝并重新命名为“~/.ssh/config”。
标准的配置文件大概是这样的:
[lots of explanations and possible options listed]
# Be paranoid by default
Host *
ForwardAgent no
ForwardX11 no
FallBackToRsh no
还有很多选项的设置可以用“man ssh”查看“CONFIGURATION FILES”这一章。
配置文件是按顺序读取的。先设置的选项先生效。
假定你在www.foobar.com上有一个名为“bilbo”的帐号。而且你要把“ssh-agent”和“ssh-add”结合起来使用并且使用 数据压缩来加快传输速度。因为主机名太长了,你懒得输入这么长的名字,用“fbc”作为“www.foobar.com”的简称。你的配置文件可以是这样 的:
Host *fbc
HostName www.foobar.com
User bilbo
ForwardAgent yes
Compression yes
# Be paranoid by default
Host *
ForwardAgent no
ForwardX11 no
FallBackToRsh no
你输入“ssh fbc”之后,SSH会自动地从配置文件中找到主机的全名,用你的用户名登录并且用“ssh-agent”管理的密匙进行安全验证。这样很方便吧!
用SSH连接到其它远程计算机用的还是“paranoid(偏执)”默认设置。如果有些选项没有在配置文件或命令行中设置,那么还是使用默认的“paranoid”设置。
在我们上面举的那个例子中,对于到www.foobar.com的SSH连接:“ForwardAgent”和“Compression”被设置为 “Yes”;其它的设置选项(如果没有用命令行参数)“ForwardX11”和“FallBackToRsh”都被设置成“No”。
其它还有一些需要仔细看一看的设置选项是:
l CheckHostIP yes
这个选项用来进行IP地址的检查以防止DNS欺骗。
l CompressionLevel
压缩的级别从“1”(最快)到“9”(压缩率最高)。默认值为“6”。
l ForwardX11 yes
为了在本地运行远程的X程序必须设置这个选项。
l LogLevel DEBUG
当SSH出现问题的时候,这选项就很有用了。默认值为“INFO”。
配置服务端的软件
SSH服务器的配置使用的是“/etc/ssh/sshd_config”配置文件,这些选项的设置在配置文件中已经有了一些说明而且用“man sshd”也可以查看帮助。请注意OpenSSH对于SSH 1.x和2.x没有不同的配置文件。
在默认的设置选项中需要注意的有:
l PermitRootLogin yes
最好把这个选项设置成“PermitRootLogin without-password”,这样“root”用户就不能从没有密匙的计算机上登录。把这个选项设置成“no”将禁止“root”用户登录,只能用“su”命令从普通用户转成“root”。
l X11Forwarding no
把这个选项设置成“yes”允许用户运行远程主机上的X程序。就算禁止这个选项也不能提高服务器的安全因为用户可以安装他们自己的转发器(forwarder),请参看“man sshd”。
l PasswordAuthentication yes
把这个选项设置为“no”只允许用户用基于密匙的方式登录。这当然会给那些经常需要从不同主机登录的用户带来麻烦,但是这能够在很大程度上提高系统的安全性。基于口令的登录方式有很大的弱点。
l # Subsystem /usr/local/sbin/sftpd
把最前面的#号去掉并且把路径名设置成“/usr/bin/sftpserv”,用户就能使用“sftp”(安全的FTP)了(sftpserv在 sftp软件包中)。因为很多用户对FTP比较熟悉而且“scp”用起来也有一些麻烦,所以“sftp”还是很有用的。而且2.0.7版本以后的图形化的 ftp工具“gftp”也支持“sftp”。
拷贝文件
用“scp”拷贝文件
SSH提供了一些命令和shell用来登录远程服务器。在默认情况下它不允许你拷贝文件,但是还是提供了一个“scp”命令。
假定你想把本地计算机当前目录下的一个名为“dumb”的文件拷贝到远程服务器www.foobar.com上你的家目录下。而且你在远程服务器上的帐号名为“bilbo”。可以用这个命令:
scp dumb bilbo@www.foobar.com:.
把文件拷贝回来用这个命令:
scp bilbo@www.foobar.com:dumb .
“scp”调用SSH进行登录,然后拷贝文件,最后调用SSH关闭这个连接。
如果在你的“~/.ssh/config”文件中已经为www.foobar.com做了这样的配置:
Host *fbc
HostName www.foobar.com
User bilbo
ForwardAgent yes
那么你就可以用“fbc”来代替“bilbo@www.foobar.com”,命令就简化为“scp dumb fbc:.”。
“scp”假定你在远程主机上的家目录为你的工作目录。如果你使用相对目录就要相对于家目录。
用“scp”命令的“-r”参数允许递归地拷贝目录。“scp”也可以在两个不同的远程主机之间拷贝文件。
有时候你可能会试图作这样的事:用SSH登录到www.foobar.com上之后,输入命令“scp [local machine]:dumb .”想用它把本地的“dumb”文件拷贝到你当前登录的远程服务器上。这时候你会看到下面的出错信息:
ssh: secure connection to [local machine] refused
之所以会出现这样的出错信息是因为你运行的是远程的“scp”命令,它试图登录到在你本地计算机上运行的SSH服务程序……所以最好在本地运行“scp”除非你的本地计算机也运行SSH服务程序。
用“sftp”拷贝文件
如果你习惯使用ftp的方式拷贝文件,可以试着用“sftp”。“sftp”建立用SSH加密的安全的FTP连接通道,允许使用标准的ftp命令。还有 一个好处就是“sftp”允许你通过“exec”命令运行远程的程序。从2.0.7版以后,图形化的ftp客户软件“gftp”就支持“sftp”。
如果远程的服务器没有安装sftp服务器软件“sftpserv”,可以把“sftpserv”的可执行文件拷贝到你的远程的家目录中(或者在远程计算 机的$PATH环境变量中设置的路径)。“sftp”会自动激活这个服务软件,你没有必要在远程服务器上有什么特殊的权限。
用“rsync”拷贝文件
“rsync”是用来拷贝、更新和移动远程和本地文件的一个有用的工具,很容易就可以用“-e ssh”参数和SSH结合起来使用。“rsync”的一个优点就是,不会拷贝全部的文件,只会拷贝本地目录和远程目录中有区别的文件。而且它还使用很高效 的压缩算法,这样拷贝的速度就很快。
用“加密通道”的ftp拷贝文件
如果你坚持要用传统的FTP客户软件。SSH可以为几乎所有的协议提供“安全通道”。FTP是一个有一点奇怪的协议(例如需要两个端口)而且不同的服务程序和服务程序之间、客户程序和客户程序之间还有一些差别。
实现“加密通道”的方法是使用“端口转发”。你可以把一个没有用到的本地端口(通常大于1000)设置成转发到一个远程服务器上,然后只要连接本地计算机上的这个端口就行了。有一点复杂是吗?
其实一个基本的想法就是,转发一个端口,让SSH在后台运行,用下面的命令:
ssh [user@remote host] -f -L 1234:[remote host]:21 tail -f /etc/motd
接着运行FTP客户,把它设置到指定的端口:
lftp -u [username] -p 1234 localhost
当然,用这种方法很麻烦而且很容易出错。所以最好使用前三种方法。
用SSH设置“加密通道”
“加密通道”的基础知识
SSH的“加密通道”是通过“端口转发”来实现的。你可以在本地端口(没有用到的)和在远程服务器上运行的某个服务的端口之间建立“加密通道”。然后只 要连接到本地端口。所有对本地端口的请求都被SSH加密并且转发到远程服务器的端口。当然只有远程服务器上运行SSH服务器软件的时候“加密通道”才能工 作。可以用下面命令检查一些远程服务器是否运行SSH服务:
telnet [full name of remote host] 22
如果收到这样的出错信息:
telnet: Unable to connect to remote host: Connection refused
就说明远程服务器上没有运行SSH服务软件。
端口转发使用这样的命令语法:
ssh -f [username@remote host] -L [local port]:[full name of remote host]:[remote port] [some command]
你不仅可以转发多个端口而且可以在“~/.ssh/config”文件中用“LocalForward”设置经常使用的一些转发端口。
为POP加上“加密通道”
你可以用POP协议从服务器上取email。为POP加上“加密通道”可以防止POP的密码被网络监听器(sniffer)监听到。还有一个好处就是SSH的压缩方式可以让邮件传输得更快。
假定你在pop.foobar.com上有一个POP帐号,你的用户名是“bilbo”你的POP口令是“topsecret”。用来建立SSH“加密通道”的命令是:
ssh -f -C bilbo@pop.foobar.com -L 1234:pop.foobar.com:110 sleep 5
(如果要测试,可以把“sleep”的值加到500)。运行这个命令之后会提示你输入POP口令:
bilbo@pop.foobar.com's password:
输入口令之后就可以用“telnet”连接到本地的转发端口了。
telnet localhost 1234
你会收到远程mail服务器的“READY”消息。
当然,这个方法要求你手工输入所有的POP命令,这是很不方便的。可以用Fetchmail(参考how to configure Fetchmail)。Secure POP via SSH mini-HOWTO、man fetchmail和在“/usr/doc/fetchmail-[…]”目录下的Fetchmail的FAQ都提供了一些具体的例子。
请注意IMAP协议使用的是不同的端口:IMAP v2的端口号为143而IMAP v3的端口号为220。
为X加上“加密通道”
如果你打算在本地计算机上运行远程SSH服务器上的X程序,那么登录到远程的计算机上,创建一个名为“~/.ssh/environment”的文件并加上这一行:
XAUTHORITY=/home/[remote user name]/.Xauthority
(如果在远程主机上你的家目录下不存在“.Xauthority”这个文件,那么当用SSH登录的时候就会自动创建)。
比如启动一个X程序(xterm)可以这个命令:
ssh -f -X -l [remote user name] [remote machine] xterm
这将在远程运行xterm这个程序。其它的X程序也是用相同的方法。
为linuxconf加上“加密通道”
Linuxconf是Linux的配置工具,它支持远程管理。Linuxconf的FAQ重说明了如何通过SSH使用linuxconf:
其命令为:
remadmin --exec [link_command] linuxconf --guiproto
如果你想在两台计算机之间用加密的方式传送信息,那么最好用ssh。命令是:
remadmin --exec ssh -l [account] linuxconf --guiproto
这是非常有效的而且运行用图形界面管理计算机。
这种方法需要在客户端安装linuxconf。其它的方法还有直接登录到服务器上用“X11Forwarding”或字符界面运行linuxconf。
为Webmin加上“加密通道”
Webmin是一个新的基于浏览器的配置工具。它运行在1000端口。你可以用SSH的“端口转发”对它进行加密:
ssh -f -l [remote user name] [remote host] -L 1234:[remote host]:10000 tail -f /etc/motd
把浏览器指向
http://localhost:1234'

本文转自
http://hi.baidu.com/wader2006/blog/item/8c6c7bf4f9a9cfd8f2d385bb.html

---------------------
SSH服务连接时常见问题解答
什么是SSH呢?
SSH的英文全称是Secure SHell。通过使用SSH,你可以把所有传输的数据进行加密,这样"中间人"这种攻击方式就不可能实现了,而且也能够防止DNS和IP欺骗。还有一个额 外的好处就是传输的数据是经过压缩的,所以可以加快传输的速度。SSH有很多功能,它既可以代替telnet,又可以为ftp、pop、甚至ppp提供一 个安全的"通道"。SSH客户端与服务器端通讯时,用户名及口令均进行了加密,有效防止了对口令的窃听。最初SSH是由芬兰的一家公司开发的。但是因为受 版权和加密算法的限制,现在很多人都转而使用OpenSSH。OpenSSH是SSH的替代软件,而且是免费的,可以预计将来会有越来越多的人使用它而不 是SSH。SSH是由客户端和服务端的软件组成的。SSH安装容易、使用简单,而且比较常见,一般的Unix系统、Linux系统、FreeBSD系统都 附带有支持SSH的应用程序包。
SSH的安全验证是如何工作的? 从客户端来看,SSH提供两种级别的安全验证。 第一种级别(基于口令的安全验证)只要你知道自己帐号和口令,就可以登录到远程主机。所有传输的数据都会被加密,但是不能保证你正在连接的服务器就是你想 连接的服务器。可能会有别的服务器在冒充真正的服务器,也就是受到"中间人"这种方式的攻击。 第二种级别(基于密匙的安全验证)需要依靠密匙,也就是你必须为自己创建一对密匙,并把公用密匙放在需要访问的服务器上。如果你要连接到SSH服务器上, 客户端软件就会向服务器发出请求,请求用你的密匙进行安全验证。服务器收到请求之后,先在你在该服务器的家目录下寻找你的公用密匙,然后把它和你发送过来 的公用密匙进行比较。如果两个密匙一致,服务器就用公用密匙加密"质询"(challenge)并把它发送给客户端软件。
客户端软件收到"质询"之后就可以用你的私人密匙解密再把它发送给服务器。 用这种方式,你必须知道自己密匙的口令。但是,与第一种级别相比,第二种级别不需要在网络上传送口令。 第二种级别不仅加密所有传送的数据,而且"中间人"这种攻击方式也是不可能的(因为他没有你的私人密匙)。但是整个登录的过程可能需要10秒。 命令的格式 首先、确保server端的ssh服务是开的(service shhd start) 然后在client端输入: ssh usrname@serverip (远程登录) scp filename usrname@serverip:/URL (远程传输)
常出现的问题:
问题一 ssh登录的时候链接端口失败 提示(1): # ssh 172.16.81.221 ssh: connect to host 172.16.81.221 port 22: No route to host 这由于server端没有开机或是网络不通(这个原因很多,最简单的是网线没有插。还有就是可能会是网卡down了等) 提示(2): # ssh work@172.16.81.221 ssh: connect to host 172.16.81.221 port 22: Connection refused 这是由于对方server的ssh服务没有开。这个server端开启服务即可。
问题二、 ssh到server上的时候密码是对的但是报如下信息: # ssh 172.16.81.221 root@172.16.81.221's password: Permission denied, please try again. 这个是由于如果不输入用户名的时候默认的是root用户,但是安全期间ssh服务默认没有开root用户的ssh权限 解决方法: 要修改root的ssh权限,即修改 /etc/ssh/sshd_config文件中 PermitRootLogin no 改为 PermitRootLogin yes
问题三 登录是出现如下提示: ssh root@172.16.81.221 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that the RSA host key has just been changed. The fingerprint for the RSA key sent by the remote host is 76:fb:b3:70:14:48:19:d6:29:f9:ba:42:46:be:fb:77. Please contact your system administrator. Add correct host key in /home/fante/.ssh/known_hosts to get rid of this message. Offending key in /home/fante/.ssh/known_hosts:68 RSA host key for 172.16.81.221 has changed and you have requested strict checking. Host key verification failed. server端密码或是其他发生改变的时候。解决方法一般就需要删除~/.ssh/known_hosts的对应行,然后再登录即可。
-------------------------------------------------------------------------------------------------------

MyEnTunnel/PuTTY/Plink速度之所以慢是因为plink的问题,MyEnTunnel/PuTTY都是plink的前端调用的都是 plink,plink的beta版是有问题的它的速度不会高于40KB/s的无论你的ssh服务器速度多快,这个问题在plink的dev版中得到了解 决,也就是说使用dev版的plink时就不会有速度慢的情况了这大概也是有的人改用Tunnelier后速度没有变化的原因了,大家可以测试下使用 plink的beta版http://putty.very.rulez.org/latest/x86/plink.exe和使用dev版http: //tartarus.org/~simon/putty-snapshots/x86/plink.exe速度的差别,提供的ssh账号供测试主机 174.132.165.34 端口 22 用户 site5 密码 demodemo测试后你就会发现使用plink的dev版速度和使用Tunnelier是一样的明显高于plink的beta版!呵呵,这样你就不要忍 受体积庞大的Tunnelier了,可以继续使用简单方便的MyEnTunnel了,你只需要把你的plink改为dev版,快点下载http://tartarus.org/~simon/putty-snapshots/x86/plink.exe替换吧.
-------------------------------------------

Tunnelier使用教程

建议用 Tunnelier代替MyEnTunnel翻墙以提高SSH速度:

MyEnTunnel实际上是plink的gui前端而已,可以避免记忆复杂的命令行,还可以安全的保存密码。 很多人用MyEnTunnel做为windows下的ssh客户端翻墙。

但是有个问题,通过MyEnTunnel或者plink下载或者看视频速度很慢,最高不超过35KB/s。

我尝试修改sshd的配置,给openssh-server打补丁(http://www.psc.edu/index.php/hpn-ssh,
http://web.archive.org/web/20110221092606/http://wiki.ramp.org.au/pages/viewpage.action?pageId=3768464),优化TCP参数(http://web.archive.org/web/20120329184816/http://blog.omobox.com/2008/06/02/linux-sysctl),都无济于事。然后在本地 的Linux虚拟机上运行ssh -D …命令,发现速度飞快,没有任何限制了。原来问题在客户端,可能是plink or putty做了什么限制吧。

推荐Tunnelier,另一款ssh客户端,对个人用户免费。下载地址:http://www.bitvise.com/tunnelier-download

软件设置比较简单:
Login选项卡,输入ssh服务器的登录信息。
Options选项卡,On Login部分把几个勾都去掉,只是翻墙的话用不上。
Services选项卡,SOCKS/HTTP Proxy Forwarding部分 Enabled,修改本地监听端口。
然后Save Profile As另存配置

Tips:
可以从命令行运行 Tunnelier:tunnelier -profile=profilename.tlp -loginOnStartup
可以把上面的命令做成快捷方式放到启动里面.
----------------------------

不是所有 Linux 软件都能支持代理服务器。如果你最热爱的 Linux 工具需要访问”被封”的网站,又没有嵌入的代理支持,该怎么办呢?
遇到这种情况当然不要放弃该软件… 毕竟我们用的系统是 Linux 而不是以前让我们咳声叹气,丧失信心的 Windows,总有一个方法去解决问题。
举个例子吧
我不久前发现了 Twitter 这个网站。我一开始不经常用,也搞不明白别人为什么对这个 web 2.0 服务都着了迷。后来我在推特上跟的人越来越多,跟着我的人亦是日益增多,不知不觉我也迷上了该网站,天天都会上。凡是经常用推特的人一般都会用一个推特的 客户端,这才能跟得上朋友们的状态更新和最火热的网络新闻。本人作为 Ubuntu 的用户,我自然就选了 Gwibber 这个基于 GNOME 的客户端来访问我的推特。这个软件功能很丰富,用起来得心应手,不过总有一个问题让我有点遗憾,就是 Gwibber 还不听从 GNOME 的代理设置。 平时这也不是一个很大的问题,但是每遇中国网络封锁较严重时,都会让我暂时无法使用该软件。
解决方案…
经过几个 Google 搜索,我最终很高兴地发现 Linux 有一个能够强迫任何软件通过 SOCKS 代理上网的工具,这个工具就是 proxychains。 以下有配置方法:
sudo apt-get install proxychains
修改配置文件 (/etc/proxychains.conf),应该如下:
# sudo nano /etc/proxychains.conf
# proxychains.conf  VER 2.0
#
#        HTTP, SOCKS4, SOCKS5 tunneling proxifier.
#

# The option below identifies how the ProxyList is treated.
# only one option should be uncommented at time,
# otherwise the last appearing option will be accepted
#
# Dynamic - Each connection will be done via chained proxies
# all proxies chained in the order as they appear in the list
# at least one proxy must be online to play in chain
# (dead proxies are skipped)
# otherwise EINTR is returned to the app
#
# Strict - Each connection will be done via chained proxies
# all proxies chained in the order as they appear in the list
# all proxies must be online to play in chain
# otherwise EINTR is returned to the app
#
# Random - Each connection will be done via random proxy
# (or proxy chain, see  chain_len) from the list
# this option is good for scans

dynamic_chain
#strict_chain
#random_chain

# Make sense only if random_chain
chain_len = 2

# Quiet mode (no output)
#quiet_mode

# Write stats about good proxies to proxychains.stats
#write_stats

#Some timeouts in milliseconds
#
tcp_read_time_out 15000
tcp_connect_time_out 10000

[ProxyList]
# ProxyList format
#       type  host  port [user pass]
#       (values separated by 'tab' or 'blank')
#
#
#        Examples:
#
#             socks5 192.168.67.78 1080 lamer  secret
#  http 192.168.89.3 8080 justu hidden
#   socks4 192.168.1.49 1080
#         http 192.168.39.93 8080
#
#
#       proxy types: http, socks4, socks5
#        ( auth types supported: "basic"-http  "user/pass"-socks )
#
#http  10.0.0.5 3128
socks5 127.0.0.1 9999
socks4 127.0.0.1 9050
注意事项:
  1. 要选 dynamic_chain 而不是 random_chain
  2. 可以列举几个代理服务器,proxychains 会按顺序用,代理无法访问即自动选用下一个
  3. 代理服务器要根据自己电脑的情况自行调整
运行 proxychains
在终端中:
proxychains 你的软件 
比如说:
proxychains chromium-browser 
我还是推荐你使用 proxychains.
---------------------------------

ProxyChains 

现在我们可以用 FireFox 及 Chrome 通过 SSH Tunneling 来访问之前无法访问的网站了,但有些程序本身不支持 Socket 5 代理,那么我们可以通过 ProxyChains来实现。

ProxyChains

ProxyChains 是一个类似于 windows下proxifier的软件,可结合 ssh tunneling 功能来实现翻墙。
安装
sudo apt-get install proxychains
配置,修改 /etc/proxychains.conf
# proxychains.conf  VER 2.0
#
#        HTTP, SOCKS4, SOCKS5 tunneling proxifier.
#

# The option below identifies how the ProxyList is treated.
# only one option should be uncommented at time,
# otherwise the last appearing option will be accepted
#
# Dynamic - Each connection will be done via chained proxies
# all proxies chained in the order as they appear in the list
# at least one proxy must be online to play in chain
# (dead proxies are skipped)
# otherwise EINTR is returned to the app
#
# Strict - Each connection will be done via chained proxies
# all proxies chained in the order as they appear in the list
# all proxies must be online to play in chain
# otherwise EINTR is returned to the app
#
# Random - Each connection will be done via random proxy
# (or proxy chain, see  chain_len) from the list
# this option is good for scans

dynamic_chain
#strict_chain
#random_chain

# Make sense only if random_chain
chain_len = 2

# Quiet mode (no output)
#quiet_mode

# Write stats about good proxies to proxychains.stats
#write_stats

#Some timeouts in milliseconds
#
tcp_read_time_out 15000
tcp_connect_time_out 10000

[ProxyList]
# ProxyList format
#       type  host  port [user pass]
#       (values separated by 'tab' or 'blank')
#
#
#        Examples:
#
#             socks5 192.168.67.78 1080 lamer  secret
#  http 192.168.89.3 8080 justu hidden
#   socks4 192.168.1.49 1080
#         http 192.168.39.93 8080
#
#
#       proxy types: http, socks4, socks5
#        ( auth types supported: "basic"-http  "user/pass"-socks )
#
#http  10.0.0.5 3128
socks5 127.0.0.1 7070
注意选 dynamic_chain
如何使用?
比如我们可以通过 proxychains 来运行 Twitter 客户端 pino ,如下。
proxychains pino &
就这么简单。
另外通过 proxychains来安装来自于 PPA 的软件可以起到增速的作用。
sudo proxychains apt-get install software-name
------------------------------------------------------------------------------------
Ubuntu PPA 是什么?

定义:

Personal Package Archives 个人软件包档案

Personal Package Archives(个人软件包档案)是Ubuntu Launchpad网站提供的一项服务,
允许个人用户上传软件源代码,通过Launchpad进行编译并发布为2进制软件包,作为apt/新
立得源供其他用户下载和更新。在Launchpad网站上的每一个用户和团队都可以拥有一个或
多个PPA。

使用
用 SSH 代理为 PPA 增速

用proxychains运行apt-get
<code>
sudo proxychains apt-get update
sudo proxychains apt-get upgrade

参考

Avant Window Navigator for Ubuntu Linux http://www.howtogeek.com/howto/2934/avant-window-navigator-installation-and-configuration-guide/
------------------------------------------------------
Ubuntu篇

安装proxychains
sudo apt-get install proxychains

修改配置文件 (/etc/proxychains.conf),找到下面的几行,把它们前面的#号去掉:
dynamic_chain
chain_len = 2
tcp_read_time_out 15000
tcp_connect_time_out 10000
[ProxyList]
http 10.0.0.5 3128
socks5 127.0.0.1 1080
socks4 127.0.0.1 9050

空间探测站提醒:代理可以列举多个个代理服务器,proxychains会按顺序来优先使用,如果无法访问会自动选用下一个。

软件通过proxychains实现代理的方法,在终端中输入的命令格式如下:
proxychains 你的软件

比如说启动火狐浏览器就用以下命令:
proxychains firefox
-----------------------------------------
六大加密工具让数据传送安然无恙
加密即将数据从其原始形式转换为一种只能由解密者阅读的形式。从本质上讲,加密的目的是为了防止对数据的未授权阅读。加密技术可从不同角度阐述,今天我们 仅介绍六个最著名的加密工具。
1. GnuPG / PGP:这两种工具可以保障文件和通信的高级加密。PGP是由Phil Zimmerman开发的著名加密程序,它可以帮助我们对数据加密,防止窃听和其它的风险。GnuPG是一个有着良好口碑的PGP标准的开源实现,它不但 可以加密,而且支持对你的数据和通信进行数字签名。GnuPG也称为GPG,是一个命令行工具,它可以与其它的应用程序集成。拥有大量的前端应用程序、 库。GnuPG一直免费,而PGP的某些应用需要花钱。

2. OpenSSL :它被称为首要的SSL/TLS加密库。OpenSSL项目是一个强健的、商业级的开源工具,其特性很多。它支持SSL (SSL v2/v3)和传输层安全协议(TLS V1)以及通用的加密库。此项目由全世界使用互联网通信的志愿者团体管理,他们还负责其相关文档的编制。
3. Tor :对于使用互联网通信的公司来说,Tor是一个不错的工具,它可以改善其通信的安全性。用Tor可以帮助用户使web的浏览和发布、即时通信、SSH和其 它使用TCP协议的应用程序匿名化。Tor还提供一个平台,开发人员可以在其上用内置的匿名性、安全性和私密性构建新的应用程序。不过,对于欲使用免费的 跨平台的GUI用户而言,我们推荐Vidalia。
4. Stunnel:这是一个通用的SSL加密程序。Stunnel的设计目的是充当远程客户端和本地或远程服务器之间的一个SSL加密程序。它可以在无需改 变程序代码的情况下被用于向通用的inetd邮件收发后台程序(如POP2, POP3, 和 IMAP server)增加SSL功能。它能够使用OpenSSL和SSLeay库成功地完成一次SSL连接。
5. OpenVPN: OpenVPN是一个开源的SSL VPN程序包,它通过负载平衡、失效转移和精细的访问控制,可以提供大量的配置,包括远程访问、站点到站点的VPN、Wi-Fi安全和企业级的远程访问方 案。OpenVPN用工业标准的SSL/TLS协议来实施OSI第二层或第三层的安全网络扩展,支持基于证书、智能卡的灵活客户端验证,通过使用适应于 VPN虚拟接口的防火墙规则,允许用户或组的特定访问控制策略,它使用OpenSSL作为其首要的加密库。
6. TrueCrypt:这是一个Windows和Linux下的开源的磁盘加密软件。可以说,TrueCrypt是一个出色的磁盘加密系统。用户可以用它来 加密整个文件系统,无需用户干预,它就能够实现动态的加密和解密。它可以在一个文件内部创建一个虚拟的加密磁盘,并以一个真实的磁盘的身份装载它,它可以 加密整个的硬盘分区或一个存储设备(如一个USB闪速驱动器)。
-----------------------------------------------------------------------------------------------------
In this Tutorial I'll cover how you can tunnel any TCP traffic through an encrypted SSH connection or a SOCKS server, even if a certain program doesn't support proxying of connections natively.
The only requirement for SSH tunneling to work is a shell account on a machine connected to the internet (and, optionally, a HTTP Proxy server). I will refer to this account as your server (it doesn't matter if you may not become root).

Tunneling HTTP

In case you just want to tunnel HTTP traffic (to surf safely, to let the request appear to originate from a different IP and/or to not disclose HTTP clear text passwords to your LAN) best practise is to set up Privoxy on your server. By default, Privoxy binds to 127.0.0.1:8118 (thus only allowing connections from localhost), which is good for us. No configuration must be done for this.
The next step is to establish a tunnel from your computer to your server's Privoxy. That is done with the following SSH command:
ssh -NL 8118:localhost:8118 user@server
This command opens a tunnel on your computer: All connections to port 8118 will be forwarded (encrypted, of course) over the SSH connection and come out at your server's port 8118 (where Privoxy is running).
Once you have established the connection you will want to edit your browser's proxy settings accordingly. Just set the HTTP (and, with some browsers, the HTTPS) proxy to localhost, port 8118.

Advantages

The great advantage over SOCKS tunneling (see below) is, that even the DNS requests are made from your server. No-one on your LAN can gather information on what kind of site you're surfing. Another advantage is that Privoxy already filters out some advertisements and removes sensitive headers from your requests.

Tunneling Arbitrary Protocols (Dynamic Forward/SOCKS)

If you want to tunnel not just HTTP traffic but arbitrary other TCP protocols as well, a HTTP Proxy isn't adequate any more. Instead, you'll have to set up a SOCKS proxy. That also is possible with SSH:

Setting up the SSH proxy

Setting up the SSH SOCKS proxy is really easy. On your computer, just enter the following command:
ssh -ND 3333 user@server
That command establishes a connection to your server, logs in as user user (you'll have to enter your password though, of course) and then starts a little SOCKS proxy on your server.
On your computer, all connections to port 3333 will be forwarded over the secure SSH channel and will then be forwarded by the proxy to their destination.
Now you'll have to configure the program you want to connect through that tunnel to use localhost, port 3333 as it's SOCKS server (if you have the choice, select SOCKS version 5).
Not many programs support SOCKS proxy forwarding natively (hardly any CLI programs). But there is a workaround for that: proxychains. It enables arbitrary programs which don't support the SOCKS protocol natively to establish connections via a SOCKS server.
Have fun! 

from: http://www.plenz.com/tunnel-everything

---------------------------------------------------------
假设要上传的压缩包在SSH所在服务器的zip目录中,形如:zip/testupload.tar.gz ,远程服务器IP地址:125.211.218.17 远程服务器FTP用户:usename  FTP密码为:123456
我们首先登录SSH并转到zip目录下,当然就是一路的ls和cd命令。如:
cd code /*转到code目录
ls /*列出该目录所有文件
下面就是利用SSH上传的命令了:
[tyche]$ ftp /* ftp命令,启用FTP客户端
ftp> open  125.211.218.17 /*open命令,打开远程服务器IP
Connected to 125.211.218.17   /*出现连接服务器的信息
220 ProFTPD 1.2.9 Server ready.  /*出现连接服务器的信息
Name (125.211.218.17:root): username /*输入FTP用户名
331 Password required for oran.
Password: 123456 /*输入密码
230 User oran logged in.  /*已经登录完毕
put testupload.tar.gz testupload.tar.gz
/*这是关键,put是上传命令,第一个testupload.tar.gz是本服务器文件名,第二个是远程文件名。就是说把本服务器上的testupload.tar.gz 上传到远程FTP里,并且命名为testupload.tar.gz 这样。
这时候SSH就可以自己上传了。你就可以做别的事情了。待会儿回来就会看到成果了。国外服务器上传的速度是很快的。
----------------------------------

1.什么是SSH

传统的网络服务程序, 如:ftp、POP和telnet在本质上都是不安全的,因为它们在网络上用明文传送口令和数据,别有用心的人非常容易就可以 截获这些口令和数据。而且,这些服务程序的安全验证方式也是有其弱点的,就是很容易受到“中间人”(man-in-the-middle)这种方式的攻 击。所谓“中间人”的攻击方式,就是“中间人”冒充真正的服务器接收你传给服务器的数据,然后再冒充你把数据传给真正的服务器。服务器和你之间的数据传送 被“中间人”一转手做了手脚之后,就会出现很严重的问题。
从前,一个名为 Tatu Yl?nen的芬兰程序员开发了一种网络协议和服务软件,称为SSH(Secure SHell的缩写)。通过使用SSH,你可以把所有传输的数据进行加密,这样“中间人”这种攻击方式就不可能实现了,而且也能够防止DNS和IP欺骗。还 有一个额外的好处就是传输的数据是经过压缩的,所以可以加快传输的速度。SSH有很多功能,虽然许多人把Secure Shell仅当作Telnet的替代物,但你可以使用它来保护你的网络连接的安全。你可以通过本地或远程系统上的Secure Shell转发其他网络通信,如POP、X、PPP和FTP。你还可以转发其他类型的网络通信,包括CVS和任意其他的TCP通信。另外,你可以使用带 TCP包装的Secure Shell,以加强连接的安全性。除此之外,Secure Shell还有一些其他的方便的功能,可用于诸如Oracle之类的应用,也可以将它用于远程备份和像SecurID卡一样的附加认证。

2.SSH的工作机制

SSH分为两部分:客户端部分和服务端部分。
服务端是一个守护进程(demon),他在后台运行并响应来自客户端的连接请求。服务端一般是sshd进程,提供了对远程连接的处理,一般包括公共密钥认证、密钥交换、对称密钥加密和非安全连接。
客户端包含ssh程序以及像scp(远程拷贝)、slogin(远程登陆)、sftp(安全文件传输)等其他的应用程序。
他们的工作机制大致是本地的客户端发送一个连接请求到远程的服务端,服务端检查申请的包和IP地址再发送密钥给SSH的客户端,本地再将密钥发回给服务端,自此连接建立。刚才所讲的只是SSH连接的大致过程,SSH 1.x和SSH 2.x在连接协议上还有着一些差异。
SSH被设计成为工作于自己的基础之上而不利用超级服务器(inetd),虽然可以通过inetd上的tcpd来运行SSH进程,但是这完全没有必要。启动SSH服务器后,sshd运行起来并在默认的22端口进行监听(你可以用 # ps -waux | grep sshd 来查看sshd是否已经被正确的运行了)如果不是通过inetd启动的SSH,那么SSH就将一直等待连接请求。当请求到来的时候SSH守护进程会产生一个子进程,该子进程进行这次的连接处理。
但是因为受版权和加密算法的限制,现在很多人都转而使用OpenSSH。OpenSSH是SSH的替代软件,而且是免费的,
SSH是由客户端和服务端的软件组成的,有两个不兼容的版本分别是:1.x和2.x。用SSH 2.x的客户程序是不能连接到SSH 1.x的服务程序上去的。OpenSSH 2.x同时支持SSH 1.x和2.x。

3.安装使用OpenSSH

这里主要讲的是基于 FreeBSD的OpenSSH的配置,其它Unix及派生系统使用OpenSSH的方法大致相同FreeBSD中集成了 OpenSSH,在很多Linux的发行版中都没有包括OpenSSH。但是,可以从网络上下载并安装OpenSSH,他是完全免费的。(可以访问 OpenSSH的主页 http://www.openssh.org
生成密钥对
使用ssh-keygen来生成密钥对,比如要用DSA加密算法生成一个4096Bit的密钥对可以输入如下命令(具体参数请参阅man ssh-keygen):
#ssh-keygen -b 4096 -t dsa
%ssh-keygen -b 4096 -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/fdy84/.ssh/id_dsa):
(密钥对将要存的路径,括号内为默认)
Created directory '/home/fdy84/.ssh'.
Enter passphrase (empty for no passphrase):
(输入口令)
Enter same passphrase again:
(再次输入口令,千万不要忘记否则就只有从新生成密钥了)
Your identification has been saved in /home/fdy84/.ssh/id_dsa.
(你的私钥)
Your public key has been saved in /home/fdy84/.ssh/id_dsa.pub.
(你的公钥)
The key fingerprint is:
bb:1b:f5:1c:77:62:90:21:59:7e:c6:65:e5:24:c6:e5 fdy84@freebsd
密钥分发
刚才生成了一对密钥,把私钥放在自己的机器上的~/.ssh/目录下并保证访问权限是“-rw-------”(即600)。再把生成的公钥放在要连接的远程主机的~/.ssh/目录下并改名为authorized_keys,并且保证文件除了属主外没有被人修改的权限。

4.配置使用SSH

配置服务端
启动SSH服务端很简单只需要运行

# sshd

就可以了。或者在/etc/rc.conf中加入
sshd_enable="YES"
就可以在每次启动时自动运行SSH服务端了。
SSH服务端的配置使用的配置文件是“/etc/ssh/sshd_config”,并且OpenSSH1.x和2.x的服务器配置文件均为此文件。
配置客户端
客户端想连接远程服务器只需要输入
#ssh 域名(或ip)
就可以了

比如想以fdy84用户连接IP地址为192.168.0.6的一台远程服务器 需要键入
# ssh 192.168.0.6 -l fdy84
只要配置正确就可以连上远端的服务器了

5.使用Windows下的SecureCRT进行SSH连接

如果在Windows下想要通过SSH远程管理服务器怎么办?其实Windows有很多远程管理软件,我们在这主要介绍一下SecureCRT中SSH连接的使用。(以Version 4.1.1为准介绍)
Create Public Key...
SecureCRT也可以生成密钥对,不过SecureCRT最大只支持2048Bit的密钥, 点选Tools->Create Public Key...,选择密钥算法和密钥长度,输入完口令后再使劲晃鼠标以给它生成密钥的足够的随机量之后就等待计算机生成密钥对,如图


点选左上角的Connect按钮,开启Connect对话框

再点击红圈所示的New Session按钮进入Session Options对话框

在这里我们选择SSH连接,并填入要连接的主机名称(或者ip地址),用户名,再选择基于公钥方式的认证,点击Properties...进入密钥配置对话框

在红色圈所示的位置填入你的私钥文件。
现在点击刚才建立的那个连接进行SSH连接,根据提示点击几个对话框之后就连接上远程的服务器了,如图

特别要注意的是由 SecureCRT生成的密钥对和用OpenSSH生成的密钥对在格式上不一样,而且二者都只能认识自己的密钥的格式,所以在用SecureCRT同 OpenSSH连接时分别都要用它们自己的密钥格式,可以用任何一个方法生成然后使用ssh-keygen -i 把SecureCRT生成的的密钥转换成OpenSSH的密钥格式,或者用ssh-keygen -e把OpenSSH的密钥格式转换成SecureCRT能够识别的IETF SECSH格式。
虽然SSH提供基于密码的登陆,不过基于安全考虑笔者并不推荐使用这种登陆,鉴于现在机器的速度普遍已经很快,推荐使用4096位的密钥以加强安全性。
以上是关于SSH的一些简单的介绍以及使用OpenSSH和SecureCRT进行连接的一些方法.
from: http://fanqiang.chinaunix.net/safe/program/2005-03-24/3012.shtml
-----------------------------------------------------------------------------

如何使用SSH的Port Forwarding加密不安全的服务

来源:本文出自:http://www.linuxforum.net/ 作者: 吴阿亭 Jephe (2001-09-12 12:00:00)

      一。简介: 

      大多数人知道SSH是用来替代R命令集,是用于加密的远程登录,文件传输,甚至加密的 
      FTP(SSH2内置), 因此SSH成为使用极广的服务之一,不仅如此,SSH还有另一项非常有 
      用的功能,就是它的端口转发隧道功能,利用此功能,让一些不安全的服务象POP3, 
      SMTP,FTP,LDAP等等通过SSH的加密隧道传输,然后,既然这些服务本身是不安全的, 
      密码和内容是明文传送的,现在其它中间媒介也没无监听了。 

      二。图示: 

      SSH的加密隧道保护的只是中间传输的安全性,使得任何通常的嗅探工具软件无法获取发 
      送内容。如下图: 
      假设客户机和服务器都运行Linux,且以POP3为例。 


           C (pop3 server: S)              S 
        _______                         ________                 
        |     |                         |      | 
        |     |________POP3___________ >|      | 
        |_____|                         |______| 
                  (图一:正常的POP3) 


      (图一:正常的POP3) 


           C (pop3 server:C)               S (pop3 client: S) 
        _______                         ________                 
        |     |                         |      | 
        |     |--------SSH连接--------->|      | 
        |_____|                         |______| 
         
         
      (图二:SSH隧道后的POP3) 
       

      如图一: 正常的POP3连接是客户C向服务器S进行连接,C的设置是POP3服务器为S。 
      如图二: 用SSH隧道的话,客户C设置pop3服务器为自己(localhost),然后设置SSH加密 
      隧道 
      ,如果设置在同样的端口110听取C的请求,则对C来说,pop3服务器是自己本身,端口也 
      是110 对S来说,看到的pop3请求地址不是来自C,而也是自己本身,因为有了SSH隧道。 



      三。SSH隧道设置 

      1. 首先必须在C和S上安装SSH,确保SSH首先能工作。 
      2. 我们用简单的一个命令如下: 

      # ssh -C -P -f sshaccount@S -L 110:S:110 sleep 7200 

      解释如下: 
      -C 使用压缩功能,是可选的,加快速度。 

      -P 用一个非特权端口进行出去的连接。 

      -f 一旦SSH完成认证并建立port forwarding,则转入后台运行。 

      sshaccount 客户C在服务器S上的SSH连接帐号 

      -L 110:S:110 转发C对本地端口110的连接到远程服务器S的110端口。 
      也可以用高端端口(普通用户使用,因为普通用户不能在低于1024的端口上建立SSH隧道) 
      如果用高端端口,如:-L 1110:S:110,这样任何用户都可建立这种加密隧道。 

      sleep 7200 一般用于script,必须给一个命令,我们给一个sleep等待空 命令,这里为 
      2小时,你可以 
      设为更长用于保持整个连接过程, 如 sleep 100000000 。 

      四。检验 

      设置后你就可以在客户C上用 # telnet localhost 110 命令而连到 S 上收取email, 
      而整个过程也被加密。 

      五。其它常见问题: 

      1. 每次启动该命令时需要输入密码以验证SSH连接,你也可以用RSA键对的方法自动化 
      SSH连接。 
      看文章荟萃中的另一篇文章《如何在两台linux服务器之间用RSA键对的方法SSH/SCP不需 
      密码》 

      2. 如果你希望上面的命令永远保持运行状态,你可以用如下的scripts. 
      #!/bin/sh 
      while [ 1 ] ; do 
      ssh -C -P -f sshaccount@S -L 110:S:110 sleep 7200 
      sleep 1 
      done 

      3. 你可以在一个命令中用多个L 参数 ,如 -L 1110:S:110 -L 225:S:25 -L 
      389:S:389 

      4. 一些windows客户端软件,象netscape mail,不能改变pop3端口号,被强迫到110, 
      则你只能指定110 

      5. Linux下的fetchmail常用来自动接收邮件,可在.fetchmailrc中利用 
      preconnect参数预连接 ,指定上面的命令行。 

      6. 如果客户端是windows, 则可用tera Term pro,参考 
      http://www.phys.washington.edu/Computing/winftpssh.html

-----------------------------------------------------------------------


SSH的英文全称是Secure SHell。通过使用SSH,你可以把所有传输的数据进行加密,这样"中间人"这种攻击方式就不可能实现了,而且也能够防止DNS和IP欺骗。还有一个额 外的好处就是传输的数据是经过压缩的,所以可以加快传输的速度。SSH有很多功能,它既可以代替telnet,又可以为ftp、pop、甚至ppp提供一 个安全的"通道"。





统的网络服务程序,如:ftp、pop和 telnet在本质上都是不安全的,因为它们在网络上用明文传送口令和数据,别有用心的人非常容易就可以截获这些口令和数据。而且,这些服务程序的安全验 证方式也是有其弱点的,就是很容易受到"中间人"(man-in-the-middle)这种方式的攻击。所谓"中间人"的攻击方式,就是"中间人"冒充 真正的服务器接收你的传给服务器的数据,然后再冒充你把数据传给真正的服务器。服务器和你之间的数据传送被 "中间人"一转手做了手脚之后,就会出现很严重的问题。
最初SSH是由芬兰的一家公司开发的。但是因为受版权和加密算法的限制,现在很多人都转而使用OpenSSH。OpenSSH是SSH的替代软件,而且是免费的,可以预计将来会有越来越多的人使用它而不是SSH。
SSH是由客户端和服务端的软件组成的,有两个不兼容的版本分别是:1.x和2.x。用SSH 2.x的客户程序是不能连接到SSH 1.x的服务程序上去的。OpenSSH 2.x同时支持SSH 1.x和2.x。
SSH的安全验证是如何工作的

从客户端来看,SSH提供两种级别的安全验证。
第一种级别(基于口令的安全验证)只要你知道自己帐号和口令,就可以登录到远程主机。所有传输的数据都会被加密,但是不能保证你正在连接的服务器就是你想连接的服务器。可能会有别的服务器在冒充真正的服务器,也就是受到"中间人"这种方式的攻击。
第 二种级别(基于密匙的安全验证)需要依靠密匙,也就是你必须为自己创建一对密匙,并把公用密匙放在需要访问的服务器上。如果你要连接到SSH服务器上,客 户端软件就会向服务器发出请求,请求用你的密匙进行安全验证。服务器收到请求之后,先在你在该服务器的家目录下寻找你的公用密匙,然后把它和你发送过来的 公用密匙进行比较。如果两个密匙一致,服务器就用公用密匙加密"质询"(challenge)并把它发送给客户端软件。客户端软件收到"质询"之后就可以 用你的私人密匙解密再把它发送给服务器。
用这种方式,你必须知道自己密匙的口令。但是,与第一种级别相比,第二种级别不需要在网络上传送口令。
第二种级别不仅加密所有传送的数据,而且"中间人"这种攻击方式也是不可能的(因为他没有你的私人密匙)。但是整个登录的过程可能需要10秒。

安装并测试OpenSSH

因 为受到美国法律的限制,在很多Linux的发行版中都没有包括OpenSSH。但是,可以从网络上下载并安装OpenSSH(有关OpenSSH的安装和 配置请参考:http://www.linuxaid.com.cn/engineer/brimmer/html/OpenSSH.htm)。
安装完OpenSSH之后,用下面命令测试一下:
ssh -l [your accountname on the remote host] [address of the remote host]
如果OpenSSH工作正常,你会看到下面的提示信息:
The authenticity of host [hostname] can't be established.
Key fingerprint is 1024 5f:a0:0b:65:d3:82:df:ab:44:62:6d:98:9c:fe:e9:52.
Are you sure you want to continue connecting (yes/no)?
OpenSSH告诉你它不知道这台主机,但是你不用担心这个问题,因为你是第一次登录这台主机。键入"yes"。这将把这台主机的"识别标记"加到"~/.ssh/know_hosts"文件中。第二次访问这台主机的时候就不会再显示这条提示信息了。
然后,SSH提示你输入远程主机上你的帐号的口令。输入完口令之后,就建立了SSH连接,这之后就可以象使用telnet那样使用SSH了。

SSH的密匙

生成你自己的密匙对

生成并分发你自己的密匙有两个好处:
1) 可以防止"中间人"这种攻击方式
2) 可以只用一个口令就登录到所有你想登录的服务器上
用下面的命令可以生成密匙:
ssh-keygen
如果远程主机使用的是SSH 2.x就要用这个命令:
ssh-keygen -d
在同一台主机上同时有SSH1和SSH2的密匙是没有问题的,因为密匙是存成不同的文件的。
ssh-keygen命令运行之后会显示下面的信息:
Generating RSA keys: ............................ooooooO......ooooooO
Key generation complete.
Enter file in which to save the key (/home/[user]/.ssh/identity):
[按下ENTER就行了]
Created directory '/home/[user]/.ssh'.
Enter passphrase (empty for no passphrase):
[输入的口令不会显示在屏幕上]
Enter same passphrase again:
[重新输入一遍口令,如果忘记了口令就只能重新生成一次密匙了]
Your identification has been saved in /home/[user]/.ssh/identity.
[这是你的私人密匙]
Your public key has been saved in /home/[user]/.ssh/identity.pub.
The key fingerprint is: 2a:dc:71:2f:27:84:a2:e4:a1:1e:a9:63:e2:fa:a5:89 [user]@[local machine]
"ssh-keygen -d"做的是几乎同样的事,但是把一对密匙存为(默认情况下)"/home/[user]/.ssh/id_dsa"(私人密匙)和"/home/[user]/.ssh/id_dsa.pub"(公用密匙)。
现 在你有一对密匙了:公用密匙要分发到所有你想用ssh登录的远程主机上去;私人密匙要好好地保管防止别人知道你的私人密匙。用"ls -l ~/.ssh/identity"或"ls -l ~/.ssh/id_dsa"所显示的文件的访问权限必须是"-rw-------"。
如果你怀疑自己的密匙已经被别人知道了,不要迟疑马上生成一对新的密匙。当然,你还要重新分发一次公用密匙。

分发公用密匙

在每一个你需要用SSH连接的远程服务器上,你要在自己的家目录下创建一个".ssh"的子目录,把你的公用密匙"identity.pub" 拷贝到这个目录下并把它重命名为"authorized_keys"。然后执行:
chmod 644 .ssh/authorized_keys
这一步是必不可少的。如果除了你之外别人对"authorized_keys"文件也有写的权限,SSH就不会工作。
如 果你想从不同的计算机登录到远程主机,"authorized_keys"文件也可以有多个公用密匙。在这种情况下,必须在新的计算机上重新生成一对密 匙,然后把生成的"identify.pub"文件拷贝并粘贴到远程主机的"authorized_keys"文件里。当然在新的计算机上你必须有一个帐 号,而且密匙是用口令保护的。有一点很重要,就是当你取消了这个帐号之后,别忘了把这一对密匙删掉。

配置SSH

配置客户端的软件

OpenSSH 有三种配置方式:命令行参数、用户配置文件和系统级的配置文件("/etc/ssh/ssh_config")。命令行参数优先于配置文件,用户配置文件 优先于系统配置文件。所有的命令行的参数都能在配置文件中设置。因为在安装的时候没有默认的用户配置文件,所以要把 "/etc/ssh/ssh_config"拷贝并重新命名为"~/.ssh/config"。
标准的配置文件大概是这样的:
[lots of explanations and possible options listed]
# Be paranoid by default
Host *
ForwardAgent no
ForwardX11 no
FallBackToRsh no
还有很多选项的设置可以用"man ssh"查看"CONFIGURATION FILES"这一章。
配置文件是按顺序读取的。先设置的选项先生效。
假 定你在www.foobar.com上有一个名为"bilbo"的帐号。而且你要把"ssh-agent"和"ssh-add"结合起来使用并且使用数据 压缩来加快传输速度。因为主机名太长了,你懒得输入这么长的名字,用"fbc"作为"www.foobar.com"的简称。你的配置文件可以是这样的:
Host *fbc
HostName www.foobar.com
User bilbo
ForwardAgent yes
Compression yes
# Be paranoid by default
Host *
ForwardAgent no
ForwardX11 no
FallBackToRsh no
你输入"ssh fbc"之后,SSH会自动地从配置文件中找到主机的全名,用你的用户名登录并且用"ssh-agent"管理的密匙进行安全验证。这样很方便吧!
用SSH连接到其它远程计算机用的还是"paranoid(偏执)"默认设置。如果有些选项没有在配置文件或命令行中设置,那么还是使用默认的"paranoid"设置。
在 我们上面举的那个例子中,对于到www.foobar.com的SSH连接:"ForwardAgent"和"Compression"被设置为 "Yes";其它的设置选项(如果没有用命令行参数)"ForwardX11"和"FallBackToRsh"都被设置成"No"。
其它还有一些需要仔细看一看的设置选项是:
l CheckHostIP yes
这个选项用来进行IP地址的检查以防止DNS欺骗。
l CompressionLevel
压缩的级别从"1"(最快)到"9"(压缩率最高)。默认值为"6"。
l ForwardX11 yes
为了在本地运行远程的X程序必须设置这个选项。
l LogLevel DEBUG
当SSH出现问题的时候,这选项就很有用了。默认值为"INFO"。

配置服务端的软件

SSH服务器的配置使用的是"/etc/ssh/sshd_config"配置文件,这些选项的设置在配置文件中已经有了一些说明而且用"man sshd"也可以查看帮助。请注意OpenSSH对于SSH 1.x和2.x没有不同的配置文件。
在默认的设置选项中需要注意的有:
l PermitRootLogin yes
最好把这个选项设置成"PermitRootLogin without-password",这样"root"用户就不能从没有密匙的计算机上登录。把这个选项设置成"no"将禁止"root"用户登录,只能用"su"命令从普通用户转成"root"。
l X11Forwarding no
把这个选项设置成"yes"允许用户运行远程主机上的X程序。就算禁止这个选项也不能提高服务器的安全因为用户可以安装他们自己的转发器(forwarder),请参看"man sshd"。
l PasswordAuthentication yes
把这个选项设置为"no"只允许用户用基于密匙的方式登录。这当然会给那些经常需要从不同主机登录的用户带来麻烦,但是这能够在很大程度上提高系统的安全性。基于口令的登录方式有很大的弱点。
l # Subsystem /usr/local/sbin/sftpd
把 最前面的#号去掉并且把路径名设置成"/usr/bin/sftpserv",用户就能使用"sftp"(安全的FTP)了(sftpserv在sftp 软件包中)。因为很多用户对FTP比较熟悉而且"scp"用起来也有一些麻烦,所以"sftp"还是很有用的。而且2.0.7版本以后的图形化的ftp工 具"gftp"也支持"sftp"。

拷贝文件

用"scp"拷贝文件

SSH提供了一些命令和shell用来登录远程服务器。在默认情况下它不允许你拷贝文件,但是还是提供了一个"scp"命令。
假定你想把本地计算机当前目录下的一个名为"dumb"的文件拷贝到远程服务器www.foobar.com上你的家目录下。而且你在远程服务器上的帐号名为"bilbo"。可以用这个命令:
scp dumb bilbo@www.foobar.com:.
把文件拷贝回来用这个命令:
scp bilbo@www.foobar.com:dumb .
"scp"调用SSH进行登录,然后拷贝文件,最后调用SSH关闭这个连接。
如果在你的"~/.ssh/config"文件中已经为www.foobar.com做了这样的配置:
Host *fbc
HostName www.foobar.com
User bilbo
ForwardAgent yes
那么你就可以用"fbc"来代替"bilbo@www.foobar.com",命令就简化为"scp dumb fbc:."。
"scp"假定你在远程主机上的家目录为你的工作目录。如果你使用相对目录就要相对于家目录。
用"scp"命令的"-r"参数允许递归地拷贝目录。"scp"也可以在两个不同的远程主机之间拷贝文件。
有时候你可能会试图作这样的事:用SSH登录到www.foobar.com上之后,输入命令"scp [local machine]:dumb ."想用它把本地的"dumb"文件拷贝到你当前登录的远程服务器上。这时候你会看到下面的出错信息:
ssh: secure connection to [local machine] refused
之所以会出现这样的出错信息是因为你运行的是远程的"scp"命令,它试图登录到在你本地计算机上运行的SSH服务程序……所以最好在本地运行"scp"除非你的本地计算机也运行SSH服务程序。

用"sftp"拷贝文件

如 果你习惯使用ftp的方式拷贝文件,可以试着用"sftp"。"sftp"建立用SSH加密的安全的FTP连接通道,允许使用标准的ftp命令。还有一个 好处就是"sftp"允许你通过"exec"命令运行远程的程序。从2.0.7版以后,图形化的ftp客户软件"gftp"就支持"sftp"。
如 果远程的服务器没有安装sftp服务器软件"sftpserv",可以把"sftpserv"的可执行文件拷贝到你的远程的家目录中(或者在远程计算机的 $PATH环境变量中设置的路径)。"sftp"会自动激活这个服务软件,你没有必要在远程服务器上有什么特殊的权限。

用"rsync"拷贝文件

"rsync" 是用来拷贝、更新和移动远程和本地文件的一个有用的工具,很容易就可以用"-e ssh"参数和SSH结合起来使用。"rsync"的一个优点就是,不会拷贝全部的文件,只会拷贝本地目录和远程目录中有区别的文件。而且它还使用很高效 的压缩算法,这样拷贝的速度就很快。

用"加密通道"的ftp拷贝文件

如果你坚持要用传统的FTP客户软件。SSH可以为几乎所有的协议提供"安全通道"。FTP是一个有一点奇怪的协议(例如需要两个端口)而且不同的服务程序和服务程序之间、客户程序和客户程序之间还有一些差别。
实现"加密通道"的方法是使用"端口转发"。你可以把一个没有用到的本地端口(通常大于1000)设置成转发到一个远程服务器上,然后只要连接本地计算机上的这个端口就行了。有一点复杂是吗?
其实一个基本的想法就是,转发一个端口,让SSH在后台运行,用下面的命令:
ssh [user@remote host] -f -L 1234:[remote host]:21 tail -f /etc/motd
接着运行FTP客户,把它设置到指定的端口:
lftp -u [username] -p 1234 localhost
当然,用这种方法很麻烦而且很容易出错。所以最好使用前三种方法。

用SSH设置"加密通道"

"加密通道"的基础知识

SSH 的"加密通道"是通过"端口转发"来实现的。你可以在本地端口(没有用到的)和在远程服务器上运行的某个服务的端口之间建立"加密通道"。然后只要连接到 本地端口。所有对本地端口的请求都被SSH加密并且转发到远程服务器的端口。当然只有远程服务器上运行SSH服务器软件的时候"加密通道"才能工作。可以 用下面命令检查一些远程服务器是否运行SSH服务:
telnet [full name of remote host] 22
如果收到这样的出错信息:
telnet: Unable to connect to remote host: Connection refused
就说明远程服务器上没有运行SSH服务软件。
端口转发使用这样的命令语法:
ssh -f [username@remote host] -L [local port]:[full name of remote host]:[remote port] [some command]
你不仅可以转发多个端口而且可以在"~/.ssh/config"文件中用"LocalForward"设置经常使用的一些转发端口。

为POP加上"加密通道"

你可以用POP协议从服务器上取email。为POP加上"加密通道"可以防止POP的密码被网络监听器(sniffer)监听到。还有一个好处就是SSH的压缩方式可以让邮件传输得更快。
假定你在pop.foobar.com上有一个POP帐号,你的用户名是"bilbo"你的POP口令是"topsecret"。用来建立SSH"加密通道"的命令是:
ssh -f -C bilbo@pop.foobar.com -L 1234:pop.foobar.com:110 sleep 5
(如果要测试,可以把"sleep"的值加到500)。运行这个命令之后会提示你输入POP口令:
bilbo@pop.foobar.com's password:
输入口令之后就可以用"telnet"连接到本地的转发端口了。
telnet localhost 1234
你会收到远程mail服务器的"READY"消息。
当然,这个方法要求你手工输入所有的POP命令,这是很不方便的。可以用Fetchmail(参考
how to configure Fetchmail)。Secure POP via SSH mini-HOWTO、man fetchmail和在"/usr/doc/fetchmail-[…]"目录下的Fetchmail的FAQ都提供了一些具体的例子。
请注意IMAP协议使用的是不同的端口:IMAP v2的端口号为143而IMAP v3的端口号为220。

为X加上"加密通道"

如果你打算在本地计算机上运行远程SSH服务器上的X程序,那么登录到远程的计算机上,创建一个名为"~/.ssh/environment"的文件并加上这一行:
XAUTHORITY=/home/[remote user name]/.Xauthority
(如果在远程主机上你的家目录下不存在".Xauthority"这个文件,那么当用SSH登录的时候就会自动创建)。
比如启动一个X程序(xterm)可以这个命令:
ssh -f -X -l [remote user name] [remote machine] xterm
这将在远程运行xterm这个程序。其它的X程序也是用相同的方法。

为linuxconf加上"加密通道"

Linuxconf(http://www.solucorp.qc.ca/linuxconf/)是Linux的配置工具,它支持远程管理。Linuxconf的FAQ重说明了如何通过SSH使用linuxconf:
其命令为:
remadmin --exec [link_command] linuxconf --guiproto
如果你想在两台计算机之间用加密的方式传送信息,那么最好用ssh。命令是:
remadmin --exec ssh -l [account] linuxconf --guiproto
这是非常有效的而且运行用图形界面管理计算机。
这种方法需要在客户端安装linuxconf。其它的方法还有直接登录到服务器上用"X11Forwarding"或字符界面运行linuxconf。

为Webmin加上"加密通道"

Webmin(http://www.webmin.com/webmin/)是一个新的基于浏览器的配置工具。它运行在1000端口。你可以用SSH的"端口转发"对它进行加密:
ssh -f -l [remote user name] [remote host] -L 1234:[remote host]:10000 tail -f /etc/motd
把浏览器指向
http://localhost:1234
版权说明
这篇文章翻译和改编自:http://www.mandrakeuser.org/secure/index.html。英文版的版权属于"MandrakeSoft SA and LSTB 1999/2000"。
中文版版权归译者brimmer(brimmer@linuxaid.com.cn)和www.linuxaid.com.cn站点所有


--------------------------------------------------------------------------------
SSH有两个版本,我们现在介绍的是版本2。

   1. 安装SSH

具体步骤如下:

   1. 获得SSH软件包。 (ftp://ftp.pku.edu.cn:/pub/unix/ssh-2.3.0.tar.gz)

   2. 成为超级用户(root).
   3. # gzip –cd ssh-2.3.0.tar.gz |tar xvf –
   4. # cd ssh-2.3.0
   5. # ./configure

      注意,如果你希望用tcp_wrappers来控制SSH,那么在configure时需要加上选项“--with-libwrap=/path/to/libwrap/”, 用来告诉SSH关于libwrap.a 和tcpd.h的位置。
   6. # make
   7. # make install

和SSH有关的程序都放置在/usr/local/bin下,包括ssh,sftp,sshd2, ssh-keygen等。

二、配置

SSH的配置文件在/etc/ssh2下,其中包括sshd2的主机公钥和私钥:hostkey和hostkey.pub。这两个文件通常是在安装SSH时自动生成的。你可以通过下面的命令重新来生成它们:

# rm /etc/ssh2/hostkey*

# ssh-keygen2 –P /etc/ssh2/hostkey

而ssh2_config 文件一般情形下无需修改。

三、启动sshd2

每个要使用SSH的系统都必须在后台运行sshd2。用手工启动:

# /usr/local/bin/sshd2&

可以在“/etc/rc2.d/S99local”中加入该命令,这样系统每次启动时会自动启动sshd2。

四、用tcp_wrappers控制SSH

安装SSH的站点可以用tcp_wrappers来限制哪些IP地址可以通过ssh来访问自己。比如,在/etc/hosts.allow中加入

sshd,sshd2: 10.0.0.1

那么只有10.0.0.1可以通过ssh来访问该主机。

以上都是系统管理员完成的工作。下面我们说说普通用户如何使用SSH。

五、基本应用

每个用户在使用SSH之前,都要完成以下步骤:

   1. 在本地主机(比如,local.pku.edu.cn)上生成自己的ssh公钥和私钥。命令如下:

      local# ssh-keygen

      Generating 1024-bit dsa key pair

      1 oOo.oOo.o

      Key generated.

      1024-bit dsa, teng@ns, Fri Oct 20 2000 17:27:05

      Passphrase :************ /*在此输入你的口令,以后访问这台主机时要用。

      Again :************ /*

      Private key saved to /home1/teng/.ssh2/id_dsa_1024_a

      Public key saved to /home1/teng/.ssh2/id_dsa_1024_a.pub

      生成的私钥和公钥(id_dsa_1024_a和id_dsa_1024_a.pub)存放在你家目录的~/.ssh2目录下。和用户相关的SSH配置文 件都在~/.ssh2下。私钥由用户保存在本地主机上,而公钥需传送到远地主机的你自己的帐号的~/.ssh2下,如果你要用ssh2访问本地主机的话。

   2. 在~/.ssh2下创建“identification”文件用来说明进行身份认证的私钥。命令如下:

local:~/.ssh2# echo "IdKey id_dsa_1024_a" > identification

3.同样地,在远地主机(比如,remote.pku.edu.cn)上完成上面步骤。

4.将本地(local.pku.edu.cn)下你自己(这里是“teng”)的公钥(id_dsa_1024_a.pub)拷贝到远地主机 (remote.pku.edu.cn)上你自己家目录下的.ssh2目录下,可命名为“local.pub”,一般用ftp上传即可。

   5. 在远地主机上,你自己家目录的.ssh2目录下,创建“authorization”文件,其中指定用来进行身份认证的公钥文件。命令如下:

      remote:~/.ssh2# echo “Key local.pub” > authorization

   6. 现在你可以从本地用ssh2登录到远地系统了。命令如下:

local# ssh remote.pku.edu.cn

Passphrase for key "/home1/teng/.ssh2/id_dsa_1024_a" with comment "1024-bit dsa,

teng@ns, Fri Oct 20 2000 17:27:05":***********

这时会要你输入你的ssh口令(Passphrase)。验证通过后,即登录到remote主机上。
from http://fanqiang.chinaunix.net/app/other/2001-06-25/2782.shtml
------------------------------------------------------------------------------
安装SSH

具体步骤如下:

获得SSH软件包。 (ftp://ftp.pku.edu.cn:/pub/unix/ssh-2.3.0.tar.gz)

成为超级用户(root).

# tar zxvf ssh-2.3.0.tar.gz
# cd ssh-2.3.0
# ./configure
注意,如果你希望用tcp_wrappers来控制SSH,那么在configure时需要加上选项“--with-libwrap=/path/to/libwrap/”,
用来告诉SSH关于libwrap.a 和tcpd.h的位置。
# make
# make install

和SSH有关的程序都放置在/usr/local/bin下,包括ssh,sftp,sshd2, ssh-keygen等。


二、配置

SSH的配置文件在/etc/ssh2下,其中包括sshd2的主机公钥和私钥:hostkey和hostkey.pub。这两个文件通常是在安装SSH时自动生成的。你可以通过下面的命令重新来生成它们:

# rm /etc/ssh2/hostkey*

# ssh-keygen2 –P /etc/ssh2/hostkey

而ssh2_config 文件一般情形下无需修改。


三、启动sshd2

每个要使用SSH的系统都必须在后台运行sshd2。用手工启动:

# /usr/local/bin/sshd2&

可以在“/etc/rc2.d/S99local”中加入该命令,这样系统每次启动时会自动启动sshd2。


四、用tcp_wrappers控制SSH

安装SSH的站点可以用tcp_wrappers来限制哪些IP地址可以通过ssh来访问自己。比如,在/etc/hosts.allow中加入

sshd,sshd2: 10.0.0.1

那么只有10.0.0.1可以通过ssh来访问该主机。


以上都是系统管理员完成的工作。下面我们说说普通用户如何使用SSH。


五、基本应用

每个用户在使用SSH之前,都要完成以下步骤:


在本地主机(比如,local.pku.edu.cn)上生成自己的ssh公钥和私钥。命令如下:

local# ssh-keygen

Generating 1024-bit dsa key pair

1 oOo.oOo.o

Key generated.

1024-bit dsa, teng@ns, Fri Oct 20 2000 17:27:05

Passphrase :************ /*在此输入你的口令,以后访问这台主机时要用。

Again :************ /*

Private key saved to /home1/teng/.ssh2/id_dsa_1024_a

Public key saved to /home1/teng/.ssh2/id_dsa_1024_a.pub


生成的私钥和公钥(id_dsa_1024_a和id_dsa_1024_a.pub)存放在你家目录的~/.ssh2目录下。和用户相关的SSH配
置文件都在~/.ssh2下。私钥由用户保存在本地主机上,而公钥需传送到远地主机的你自己的帐号的~/.ssh2下,如
果你要用ssh2访问本地主机的话。


在~/.ssh2下创建“identification”文件用来说明进行身份认证的私钥。命令如下:


local:~/.ssh2# echo "IdKey id_dsa_1024_a" > identification


3.同样地,在远地主机(比如,remote.pku.edu.cn)上完成上面步骤。

4.将本地(local.pku.edu.cn)下你自己(这里是“teng”)的公钥(id_dsa_1024_a.pub)拷贝到远地主机
(remote.pku.edu.cn)上你自己家目录下的.ssh2目录下,可命名为“local.pub”,一般用ftp上传即可。


在远地主机上,你自己家目录的.ssh2目录下,创建“authorization”文件,其中指定用来进行身份认证的公钥文件。
命令如下:

remote:~/.ssh2# echo “Key local.pub” > authorization


现在你可以从本地用ssh2登录到远地系统了。命令如下:

local# ssh remote.pku.edu.cn

Passphrase for key "/home1/teng/.ssh2/id_dsa_1024_a" with comment "1024-bit dsa,

teng@ns, Fri Oct 20 2000 17:27:05":***********


这时会要你输入你的ssh口令(Passphrase)。验证通过后,即登录到remote主机上。




第一部分:协议概览

整个通讯过程中,经过下面几个阶段协商实现认证连接。

第一阶段:

由客户端向服务器发出 TCP 连接请求。TCP 连接建立后,客户端进入等待,服务器向客户端发送第一个报文,宣告自己
的版本号,包括协议版本号和软件版本号。协议版本号由主版本号和次版本号两部分组成。它和软件版本号一起构成形如:

"SSH-<主协议版本号>.<次协议版本号>-<软件版本号>\n"

的字符串。其中软件版本号字符串的最大长度为40个字节,仅供调试使用。客户端接到报文后,回送一个报文,内容也
是版本号。客户端响应报文里的协议版本号这样来决定:当与客户端相比服务器的版本号较低时,如果客户端有特定的
代码来模拟,则它发送较低的版本号;如果它不能,则发送自己的版本号。当与客户端相比服务器的版本号较高时,客
户端发送自己的较低的版本号。按约定,如果协议改变后与以前的相兼容,主协议版本号不变;如果不相兼容,则主主
协议版本号升高。

服务器接到客户端送来的协议版本号后,把它与自己的进行比较,决定能否与客户端一起工作。如果不能,则断开TCP
连接;如果能,则按照二进制数据包协议发送第一个二进制数据包,双方以较低的协议版本来一起工作。到此为止,这
两个报文只是简单的字符串,你我等凡人直接可读。

第二阶段:

协商解决版本问题后,双方就开始采用二进制数据包进行通讯。由服务器向客户端发送第一个包,内容为自己的 RSA主
机密钥(host key)的公钥部分、RSA服务密钥(server key)的公钥部分、支持的加密方法、支持的认证方法、次协议版本
标志、以及一个 64 位的随机数(cookie)。这个包没有加密,是明文发送的。客户端接收包后,依据这两把密钥和被称
为cookie的 64 位随机数计算出会话号(session id)和用于加密的会话密钥(session key)。随后客户端回送一个包给服
务器,内容为选用的加密方法、cookie的拷贝、客户端次协议版本标志、以及用服务器的主机密钥的公钥部分和服务密钥
的公钥部分进行加密的用于服务器计算会话密钥的32 字节随机字串。除这个用于服务器计算会话密钥的 32字节随机字串
外,这个包的其他内容都没有加密。之后,双方的通讯就是加密的了,服务器向客户端发第二个包(双方通讯中的第一个
加密的包)证实客户端的包已收到。

第三阶段:

双方随后进入认证阶段。可以选用的认证的方法有:

(1) ~/.rhosts 或 /etc/hosts.equiv 认证(缺省配置时不容许使用它);
(2) 用 RSA 改进的 ~/.rhosts 或 /etc/hosts.equiv 认证;
(3) RSA 认证;
(4) 口令认证。

如果是使用 ~/.rhosts 或 /etc/hosts.equiv 进行认证,客户端使用的端口号必须小于1024。

认证的第一步是客户端向服务器发 SSH_CMSG_USER 包声明用户名,服务器检查该用户是否存在,确定是否需要进行认证。
如果用户存在,并且不需要认证,服务器回送一个SSH_SMSG_SUCCESS 包,认证完成。否则,服务器会送一个
SSH_SMSG_FAILURE 包,表示或是用户不存在,或是需要进行认证。注意,如果用户不存在,服务器仍然保持读取从客户端
发来的任何包。除了对类型为 SSH_MSG_DISCONNECT、SSH_MSG_IGNORE 以及 SSH_MSG_DEBUG 的包外,对任何类型的包都以
SSH_SMSG_FAILURE 包。用这种方式,客户端无法确定用户究竟是否存在。

如果用户存在但需要进行认证,进入认证的第二步。客户端接到服务器发来的 SSH_SMSG_FAILURE 包后,不停地向服务器
发包申请用各种不同的方法进行认证,直到时限已到服务器关闭连接为止。时限一般设定为 5 分钟。对任何一个申请,
如果服务器接受,就以 SSH_SMSG_SUCCESS 包回应;如果不接受,或者是无法识别,则以 SSH_SMSG_FAILURE 包回应。

第四阶段:

认证完成后,客户端向服务器提交会话请求。服务器则进行等待,处理客户端的请求。在这个阶段,无论什么请求只要成
功处理了,服务器都向客户端回应 SSH_SMSG_SUCCESS包;否则回应 SSH_SMSG_FAILURE 包,这表示或者是服务器处理请求
失败,或者是不能识别请求。会话请求分为这样几类:申请对数据传送进行压缩、申请伪终端、启动 X11、TCP/IP 端口
转发、启动认证代理、运行 shell、执行命令。到此为止,前面所有的报文都要求 IP 的服务类型(TOS)使用选项
 IPTOS_THROUGHPUT。

第五阶段:

会话申请成功后,连接进入交互会话模式。在这个模式下,数据在两个方向上双向传送。此时,要求 IP 的服务类型(TOS)
使用 IPTOS_LOWDELAY 选项。当服务器告知客户端自己的退出状态时,交互会话模式结束。

(注意:进入交互会话模式后,加密被关闭。在客户端向服务器发送新的会话密钥后,加密重新开始。用什么方法加密由
客户端决定。)

第二部分:密钥的交换和加密的启动

在服务器端有一个主机密钥文件,它的内容构成是这样的:

1. 私钥文件格式版本字符串;
2. 加密类型(1 个字节);
3. 保留字(4 个字节);
4. 4 个字节的无符号整数;
5. mp 型整数;
6. mp 型整数;
7. 注解字符串的长度;
8. 注解字符串;
9. 校验字(4 个字节);
10. mp 型整数;
11. mp 型整数;
12. mp 型整数;
13. mp 型整数;

其中 4、5、6 三个字段构成主机密钥的公钥部分;10、11、12、13 四个字段构成主机密钥的私钥部分。9、10、11、12、13
五个字段用字段 2 的加密类型标记的加密方法进行了加密。4 个字节的校验字交叉相等,即第一个字节与第三个字节相等,
第二个字节与第四个字节相等。在服务器读取这个文件时进行这种交叉相等检查,如果不满足这个条件,则报错退出。

服务器程序运行的第一步,就是按照上面的字段划分读取主机密钥文件。随后生成一个随机数,再调用函数

void rsa_generate_key
(
RSAPrivateKey *prv,
RSAPublicKey *pub,
RandomState *state,
unsigned int bits
);

生成服务密钥,服务密钥也由公钥和私钥两部分组成。上面的这个函数第一个指针参数指向服务密钥的私钥部分,第二个指
向公钥部分。然后把主机密钥的公钥部分和服务密钥的公钥部分发送给客户端。在等到客户端回应的包后,服务器用自己的
主机密钥的私钥部分和服务密钥的私钥部分解密得到客户端发来的 32 字节随机字串。然后计算自己的会话号,并用会话号
的前 16字节 xor 客户端发来的 32 字节随机字串的前 16 字节,把它作为自己的会话密钥。注意,服务器把8个字节的
 cookie、主机密钥的公钥部分、和服务密钥的公钥部分作为参数来计算自己的会话号。

再来看客户端。客户端启动后的第一步骤也是读取主机密钥。然后等待服务器主机密钥、服务密钥、和 8个字节的cookie。
注意,服务器发送来的只是主机密钥和服务密钥的公钥部分。接到包后,客户端立即把从服务器端收到cookie、主机密钥、
和服务密钥作为参数计算出会话号。从上面可以看出,服务器和客户端各自计算出的会话号实际是一样的。

随后,客户端检查用户主机列表和系统主机列表,查看从服务器收到的主机密钥是否在列表中。如果不在列表中,则把它加
入列表中。然后就生成 32 字节的随机字串,这个32 字节的随机字串就是客户端的会话密钥。客户端用 16字节的会话密钥
 xor 它的前 16 字节,把结果用服务器的主机密钥和服务密钥进行双重加密后发送给服务器。产生 32字节随机字串时,随
 机数种子由两部分组成,其中一部分从系统随机数种子文件中得到,这样来避免会话密钥被猜出。从上面服务器和客户端各
 自计算会话密钥的过程可以看出,服务器和客户端计算出的会话密钥是一样的。

上面的这几步,总结起来就要交换确定会话密钥,因为无论是 des、idea、3des、arcfour、还是 blowfish 都是对称加密方
法,只有一把密钥,双方都知道了会话密钥才能启动加密。但会话密钥不能在网络上明文传送,否则加密就失去意义了。于
是使用 RSA 公钥体系对会话密钥进行加密。

RSA 公钥体系的办法是用公钥加密私钥解密,它依据这样的数学定理:

若 p、q 是相异的两个质数,整数 r 和 m 满足
rm == 1 (mod (p-1)(q-1))
a 是任意的整数,整数 b、c 满足 b == a^m (mod pq),
c == b^r (mod pq)。则
c == a (mod pq)。

具体实现是这样的:

(1) 找三个正整数 p、q、r,其中 p、q 是相异的质数,
r 是与(p-1)、(q-1)互质的数。这三个数 p、q、r
就是私钥(private key)。
(2) 再找一个正整数 m 满足 rm == 1 (mod(p-1)(q-1))。
计算 n = pq,m、n 就是公钥(public key)。
(3) 被加密对象 a 看成是正整数,设 a < n。若 a >= n,
将 a 表示成 s (s < n,通常取 s = 2^t) 进制的,
然后对每一位分别编码。
(4) 加密:计算 b == a^m (mod n) (0 <= b < n),b 为
加密结果。
(5) 解密:计算 c == b^r (mod n) (0 <= c < n),c 为
解密结果。

从上面的数学定理可知,最后结果 c = a。

计算 RSA 密钥的方法及过程是,调用下面的函数计算 RSA公钥和 RSA 私钥:
_______________________________________________________
void rsa_generate_key
(
RSAPrivateKey *prv, RSAPublicKey *pub,
RandomState *state, unsigned int bits
)
{
MP_INT test, aux;
unsigned int pbits, qbits;
int ret;

mpz_init(&prv->q);
mpz_init(&prv->p);
mpz_init(&prv->e);
mpz_init(&prv->d);
mpz_init(&prv->u);
mpz_init(&prv->n);
mpz_init(&test);
mpz_init(&aux);

/* 计算质数 p、q 的位数 */
pbits = bits / 2;
qbits = bits - pbits;

retry0:

fprintf(stderr, "Generating p: ");

/* 生成随机质数 p */
rsa_random_prime(&prv->p, state, pbits);

retry:

fprintf(stderr, "Generating q: ");

/* 生成随机质数 q */
rsa_random_prime(&prv->q, state, qbits);

/* 判断是否 p == q,如果是返回重新生成 */
ret = mpz_cmp(&prv->p, &prv->q);
if (ret == 0)
{
fprintf(stderr,
"Generated the same prime twice!\n");
goto retry;
}
if (ret > 0)
{
mpz_set(&aux, &prv->p);
mpz_set(&prv->p, &prv->q);
mpz_set(&prv->q, &aux);
}

/* 确定 p、q 是否很接近 */
mpz_sub(&aux, &prv->q, &prv->p);
mpz_div_2exp(&test, &prv->q, 10);
if (mpz_cmp(&aux, &test) < 0)
{
fprintf(stderr,
"The primes are too close together.\n");
goto retry;
}

/* Make certain p and q are relatively prime (in case
one or both were false positives... Though this is
quite impossible). */
mpz_gcd(&aux, &prv->p, &prv->q);
if (mpz_cmp_ui(&aux, 1) != 0)
{
fprintf(stderr,
"The primes are not relatively prime!\n");
goto retry;
}

/* 从质数 p、q 导出私钥 */
fprintf(stderr, "Computing the keys...\n");
derive_rsa_keys(&prv->n, &prv->e, &prv->d,
&prv->u, &prv->p, &prv->q, 5);
prv->bits = bits;

/* 从质数 p、q 导出公钥 */
pub->bits = bits;
mpz_init_set(&pub->n, &prv->n);
mpz_init_set(&pub->e, &prv->e);

/* 测试公钥和密钥是否有效 */
fprintf(stderr, "Testing the keys...\n");
rsa_random_integer(&test, state, bits);
mpz_mod(&test, &test, &pub->n); /* must be less than n. */
rsa_private(&aux, &test, prv);
rsa_public(&aux, &aux, pub);
if (mpz_cmp(&aux, &test) != 0)
{
fprintf(stderr,
"**** private+public failed to decrypt.\n");
goto retry0;
}

rsa_public(&aux, &test, pub);
rsa_private(&aux, &aux, prv);
if (mpz_cmp(&aux, &test) != 0)
{
fprintf(stderr,
"**** public+private failed to decrypt.\n");
goto retry0;
}

mpz_clear(&aux);
mpz_clear(&test);

fprintf(stderr, "Key generation complete.\n");
}
_______________________________________________________

在上面的函数成一对密钥时,首先调用函数
_______________________________________________________

void rsa_random_prime
(
MP_INT *ret, RandomState *state,
unsigned int bits
)
{
MP_INT start, aux;
unsigned int num_primes;
int *moduli;
long difference;

mpz_init(&start);
mpz_init(&aux);

retry:

/* 挑出一个随机的足够大的整数 */
rsa_random_integer(&start, state, bits);

/* 设置最高的两位 */
mpz_set_ui(&aux, 3);
mpz_mul_2exp(&aux, &aux, bits - 2);
mpz_ior(&start, &start, &aux);
/* 设置最低的两位为奇数 */
mpz_set_ui(&aux, 1);
mpz_ior(&start, &start, &aux);

/* 启动小质数的 moduli 数 */
moduli = malloc(MAX_PRIMES_IN_TABLE * sizeof(moduli[0]));
if (moduli == NULL)
{
printf(stderr, "Cann't get memory for moduli\n");
exit(1);
}
if (bits < 16)
num_primes = 0;
/* Don\'t use the table for very small numbers. */
else
{
for (num_primes = 0;
small_primes[num_primes] != 0; num_primes++)
{
mpz_mod_ui(&aux, &start, small_primes[num_primes]);
moduli[num_primes] = mpz_get_ui(&aux);
}
}

/* 寻找一个数,它不能被小质数整除 */
for (difference = 0; ; difference += 2)
{
unsigned int i;

if (difference > 0x70000000)
{
fprintf(stderr, "rsa_random_prime: "
"failed to find a prime, retrying.\n");
if (moduli != NULL)
free(moduli);
else
exit(1);
goto retry;
}

/* 检查它是否是小质数的乘积 */
for (i = 0; i < num_primes; i++)
{
while (moduli[i] + difference >= small_primes[i])
moduli[i] -= small_primes[i];
if (moduli[i] + difference == 0)
break;
}
if (i < num_primes)
continue; /* Multiple of a known prime. */

/* 检查通过 */
fprintf(stderr, ".");

/* Compute the number in question. */
mpz_add_ui(ret, &start, difference);

/* Perform the fermat test for witness 2.
This means: it is not prime if 2^n mod n != 2. */
mpz_set_ui(&aux, 2);
mpz_powm(&aux, &aux, ret, ret);
if (mpz_cmp_ui(&aux, 2) == 0)
{
/* Passed the fermat test for witness 2. */
fprintf(stderr, "+");
/* Perform a more tests. These are probably unnecessary. */
if (mpz_probab_prime_p(ret, 20))
break; /* It is a prime with probability 1 - 2^-40. */
}
}

/* Found a (probable) prime. It is in ret. */
fprintf(stderr, "+ (distance %ld)\n", difference);

/* Free the small prime moduli; they are no longer needed. */
if (moduli != NULL)
free(moduli);
else
exit(1);

/* Sanity check: does it still have the high bit set (we might have
wrapped around)? */
mpz_div_2exp(&aux, ret, bits - 1);
if (mpz_get_ui(&aux) != 1)
{
fprintf(stderr,
"rsa_random_prime: high bit not set, retrying.\n");
goto retry;
}
mpz_clear(&start);
mpz_clear(&aux);
}
_______________________________________________________

随机产生一对大质数(p,q)。这对随机大质数要符合的条件是p 必须小于 q。然后调用下面的函数来生成公钥和私钥对的
其他组员:

static void derive_rsa_keys
(
MP_INT *n, MP_INT *e, MP_INT *d, MP_INT *u,
MP_INT *p, MP_INT *q,
unsigned int ebits
)
{
MP_INT p_minus_1, q_minus_1, aux, phi, G, F;

assert(mpz_cmp(p, q) < 0);

mpz_init(&p_minus_1);
mpz_init(&q_minus_1);
mpz_init(&aux);
mpz_init(φ);
mpz_init(&G);
mpz_init(&F);

/* 计算 p-1 和 q-1. */
mpz_sub_ui(&p_minus_1, p, 1);
mpz_sub_ui(&q_minus_1, q, 1);

/* phi = (p - 1) * (q - 1) */
mpz_mul(φ, &p_minus_1, &q_minus_1);

/* G is the number of "spare key sets" for a given
modulus n. The smaller G is, the better. The
smallest G can get is 2. */
mpz_gcd(&G, &p_minus_1, &q_minus_1);


if (mpz_cmp_ui(&G, 100) >= 0)
{
fprintf(stderr, "Warning: G=");
mpz_out_str(stdout, 10, &G);
fprintf(stderr,
" is large (many spare key sets); key may be bad!\n");
}

/* F = phi / G; the number of relative prime
numbers per spare key set. */
mpz_div(&F, φ, &G);

/* Find a suitable e (the public exponent). */
mpz_set_ui(e, 1);
mpz_mul_2exp(e, e, ebits);
mpz_sub_ui(e, e, 1); /*make lowest bit 1, and substract 2.*/
/* Keep adding 2 until it is relatively prime
to (p-1)(q-1). */
do
{
mpz_add_ui(e, e, 2);
mpz_gcd(&aux, e, φ);
}
while (mpz_cmp_ui(&aux, 1) != 0);

/* d is the multiplicative inverse of e, mod F.
Could also be mod (p-1)(q-1); however, we try to
choose the smallest possible d. */
mpz_mod_inverse(d, e, &F);

/* u is the multiplicative inverse of p, mod q,
if p < q. It is used when doing private key
RSA operations using the chinese remainder
theorem method. */
mpz_mod_inverse(u, p, q);

/* n = p * q (the public modulus). */
mpz_mul(n, p, q);

/* Clear auxiliary variables. */
mpz_clear(&p_minus_1);
mpz_clear(&q_minus_1);
mpz_clear(&aux);
mpz_clear(φ);
mpz_clear(&G);
mpz_clear(&F);
}
_______________________________________________________

最后为检验所生成的一对密钥的有效性,它调用下面的函数产生一个随机整数。
_______________________________________________________

void rsa_random_integer(MP_INT *ret, RandomState *state,
unsigned int bits)
{
unsigned int bytes = (bits + 7) / 8;
char *str = xmalloc(bytes * 2 + 1);
unsigned int i;

/* 生成一个适当大小的16进制随机数,把它转化成mp型整数 */
for (i = 0; i < bytes; i++)
sprintf(str + 2 * i, "%02x", random_get_byte(state));

/* 转化到内部表示 */
if (mpz_set_str(ret, str, 16) < 0)
{
fprintf("Intenal error, mpz_set_str returned error");
exit(1);
}
/* Clear extra data. */
memset(str, 0, 2 * bytes);
if (str != NULL)
free(str);
else
exit(1);

/* Reduce it to the desired number of bits. */
mpz_mod_2exp(ret, ret, bits);
}
_______________________________________________________

服务密钥生成后,服务器发送一个包把两把密钥发送给客户端,一个是主机密钥的公钥,另一个是服务密钥的公钥。跟
随这个包一起发送的还有服务器支持的加密类型和8个字节即64位的随机字串 cookie。客户端依据这两把密钥计算会话号,
会话号长16字节即128位。计算方法是:

会话号 = MD5(主机公钥模数 n || 服务公钥模数 n || cookie)

计算函数是:

void compute_session_id
(
unsigned char session_id[16],
unsigned char cookie[8],
unsigned int host_key_bits,
MP_INT *host_key_n,
unsigned int session_key_bits,
MP_INT *session_key_n
)
{
unsigned int bytes = (host_key_bits + 7) / 8 +
(session_key_bits + 7) / 8 + 8;
unsigned char *buf = xmalloc(bytes);
struct MD5Context md;

mp_linearize_msb_first(buf, (host_key_bits + 7 ) / 8, host_key_n);
mp_linearize_msb_first(buf + (host_key_bits + 7 ) / 8,
(session_key_bits + 7) / 8, session_key_n);
memcpy(buf + (host_key_bits + 7) / 8 + (session_key_bits + 7) / 8,
cookie, 8);
MD5Init(&md);
MD5Update(&md, buf, bytes);
MD5Final(session_id, &md);
xfree(buf);
}

void mp_linearize_msb_first
(
unsigned char *buf, unsigned int len,
MP_INT *value
)
{
unsigned int i;
MP_INT aux;
mpz_init_set(&aux, value);
for (i = len; i >= 4; i -= 4)
{
unsigned long limb = mpz_get_ui(&aux);
PUT_32BIT(buf + i - 4, limb);
mpz_div_2exp(&aux, &aux, 32);
}
for (; i > 0; i--)
{
buf[i - 1] = mpz_get_ui(&aux);
mpz_div_2exp(&aux, &aux, 8);
}
mpz_clear(&aux);
}

随后客户端计算会话密钥,计算过程是首先生成32个字节即256位随机字串:

for (i = 0; i < 32; i++)
session_key[i] = random_get_byte(state);

然后用16字节的会话号 xor 这32字的随机字串的前16字节,并安 msb 次序来排列构成一个MP型整数:

mpz_init_set_ui(&key, 0);
for (i = 0; i < 32; i++)
{
mpz_mul_2exp(&key, &key, 8);
if (i < 16)
mpz_add_ui(&key,&key, session_key[i]^session_id[i]);
else
mpz_add_ui(&key,&key, session_key[i]);
}

把结果发给服务器。在用服务器发来主机公钥和服务公钥对这个MP型整数作两次 RSA 加密后,客户端发一个包把这个
MP型整数交给服务器。跟随这个包一起还有客户端选定的加密类型。注意,在客户端,它用上面最初的32字节随机串
session_key 来作为会话密钥进行加密,而不是发给服务器的会话密钥 key。服务器接到上面MP型整数后,把它转换
成32字节即256位的字串。再用自己计算出的16字节的会话号xor 这个字串的前16字节,把结果作为会话密钥。服务器
计算自己的16字节会话号时也是把发给客户端的主机公钥、服务公钥、和16字节随机串 cookie 作为输入,因此它计算
出的会话号与客户端计算出的一样。

在这之后,所有的数据传输都用选用客户端指定的加密方法进行加密了,加密时使用上面的会话密钥。加密使用的代码
在 arcfour.c、des.c、idea.c、blowfish.c 中。

ssh 声称避免了 IP 欺骗,使用的方法在上面的密钥交换中服务器给客户端发了一个64位 cookie,要求客户端原样拷贝
送回。看不出这能避免 IP 欺骗。

第三部分:认证

RSA公钥和RSA私钥数据结构为:

typedef struct
{
unsigned int bits; /* 模数大小 */
MP_INT e; /* 公钥指数 */
MP_INT n; /* 模数 */
} RSAPublicKey;

typedef struct
{
unsigned int bits; /* 模数大小 */
MP_INT n; /* 模数 */
MP_INT e; /* 公钥指数 */
MP_INT d; /* 私钥指数 */
MP_INT u; /* Multiplicative inverse of p mod q. */
MP_INT p; /* 质数 p */
MP_INT q; /* 质数 q */
} RSAPrivateKey;

RSA 认证的过程是,客户端向服务器提交自己 RSA公钥的模数成员,服务器先读取用户 .ssh 目录中的公钥文件进行有
效性检验,再生成一个 256 位二进制随机数 cookie。随后把这个随机数 cookie 用从公钥文件读出的公钥加密后传给
客户端,客户端接到 cookie 后,先用自己的私钥解密,再对这个 cookie 和会话号计算出 16 字节的 md5水印,把两
个水印相加后发给服务器。服务器把它收到 md5水印和它自己对 cookie 和会话号计算出的水印和进行比较,如果相等,
则认证通过。

第四部分:shell 和 X11 调用

ssh 提供的一个重要功能就是 X 转发功能,它可以在客户端的显示屏上把服务器端 X 程序的运行结果以图形形式显示
出来显示在客户端的显示屏幕上。例如运行 xterm 程序启动一个 X 终端,该 X 终端窗口显示在客户端的显示屏上。

先来看看 X 窗口系统本身的情况。X 窗口系统是 UNIX的图形用户界面(GUI),它采用"客户/服务器"模式,二者之间的
通讯遵从 X 协议。每台主机运行一个 X 服务器,且只能运行一个 X 服务器,但一个 X 服务器可以控制多个显示屏幕
(显示器)。应用程序要想进行图形显示必须以客户的方式向 X 服务器提交显示请求,由 X 服务器统一控制进行显示。
用户运行 X 程序时,实际是调用 XOpenDisplay 库函数打开一个 PF_UNIX 或 TCP socket 连接到 X 服务器,然后通过
这个连接向它提交显示请求。连接建立后, X 客户所做的第一件事就是:按用户的 $DISPLAY 环境变量的值读取用户
配置文件 .Xauthority 中的显示记录,把这条记录的有关内容提交给 X 服务器进行认证。如果认证通过,就可以提交
显示请求了,这个过程称为打开一个 X 显示。作为客户的 X 程序在提交显示请求时,实际上是把 X 显示数据写入上面
打开的 socket。在打开 X 显示时,必须提供协议号、认证钥(hexkey)、和屏幕号,如果 X 服务器不是在本地运行,还
需要提供运行 X 服务器的远程主机名。这些都记录在用户配置文件 .Xauthority 中,所给的协议号、认证钥、和屏幕
号从这个列表中取出。可以用 xauth 命令来查看显示列表里的内容:

[wangdb@ /home/wangdb]> /usr/openwin/bin/xauth list
***.***.***/unix:10 MIT-MAGIC-COOKIE-1 \
92b404e556588ced6c1acd4ebf053f68
***.***.***/unix:11 MIT-MAGIC-COOKIE-1 \
92b404e556588ced6c1acd4ebf053f68
***.***.***:10 MIT-MAGIC-COOKIE-1 \
92b404e556588ced6c1acd4ebf053f68
***.***.***/unix:10 MIT-MAGIC-COOKIE-1 \
92b404e556588ced6c1acd4ebf053f68
***.***.***:11 MIT-MAGIC-COOKIE-1 \
92b404e556588ced6c1acd4ebf053f68
***.***.***/unix:11 MIT-MAGIC-COOKIE-1 \
92b404e556588ced6c1acd4ebf053f68
[wangdb@ /home/wangdb]> echo $DISPLAY
***.***.***:10.0
[wangdb@ /home/wangdb]> /usr/openwin/bin/xauth
Using authority file /home/wangdb/.Xauthority
xauth> list ***.***.***:10.0
***.***.***:10 MIT-MAGIC-COOKIE-1 \
92b404e556588ced6c1acd4ebf053f68
xauth> quit
[wangdb@ /home/wangdb]>

.Xauthority 文件的显示记录里各个字段的含义如下,第一个字段的***.***.*** 是主机名,":"号后的"."前面的数字
是 X 服务器标号,"."后面的数字是显示屏幕(显示器)标号。这个字段称为显示名,$DISPLAY 环境变量里填入这个字段。
第二个字段是协议标号,第三个字段是十六进制的认证钥。认证钥是由系统给的,打开 X 显示时如果认证钥给的不对,
X 服务器拒绝处理显示请求。

ssh 实现 X 转发的第一步是,客户端调用 popen 函数执行 "xauth list $DISPLAY" 命令,读取 X 显示的屏幕号、协议
号、和认证钥,然后把协议号和认证钥保存在内存中。客户端并不把自己的认证钥发送给服务器,而是生成一个 8位二进
制随机数序列,以十六进制打印,把这个十六进制数字串发送给服务器作为认证钥。等到服务器发来打开 X 显示请求时,
客户端使用自己真正的认证钥打开 X 显示。采用这种方法,客户保证了自己的认证钥不会泄露给外界,安全性得到保证。

服务器接到客户端的 X 转发请求后,读取客户端发来的屏幕号、协议号、和认证钥,然后打开一个 socket 并绑定它,
设置成侦听模式,并用这个 socket 设置一个通道。随后就从服务器自己的配置文件读出 X 服务器标号,调用
gethostname函数获取本机主机名,把这两者和客户发来的屏幕号结合在一起构成显示列表记录的第一字段。

在服务器处理客户端执行命令或启动 shell 的请求时,它用前面设置的通道接受一个 TCP 连接,返回一个 socket,
再用这个 socket 设置一个新通道。然后发一个包给客户端要求它打开一个 X 显示。客户端接到这个包后打开一个
socket 与本地 X 服务器连接,即打开一个 X 显示:
_____________________________________________________
int display_number, sock;
const char *display;
struct sockaddr_un ssun;

/* Try to open a socket for the local X server. */
display = getenv("DISPLAY");
if (!display)
{
error("DISPLAY not set.");
goto fail;
}

/* Now we decode the value of the DISPLAY variable
* and make a connection to the real X server.
*/

/* Check if it is a unix domain socket. Unix domain
* displays are in one of the following formats:
* unix:d[.s], :d[.s], ::d[.s]
*/
if (strncmp(display, "unix:", 5) == 0 ||
display[0] == ':')
{
/* Connect to the unix domain socket. */
if (sscanf(strrchr(display, ':') + 1,
"%d", &display_number) != 1)
{
error("Could not parse display number "
"from DISPLAY: %.100s", display);
goto fail;
}
/* Create a socket. */
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock < 0)
{
error("socket: %.100s", strerror(errno));
goto fail;
}
/* Connect it to the display socket. */
ssun.sun_family = AF_UNIX;
#ifdef HPSUX_NONSTANDARD_X11_KLUDGE
{
/* HPSUX release 10.X uses
* /var/spool/sockets/X11/0
* for the unix-domain sockets, while earlier
* releases stores the socket in
* /usr/spool/sockets/X11/0
* with soft-link from
* /tmp/.X11-unix/`uname -n`0
*/

struct stat st;

if (stat("/var/spool/sockets/X11", &st) == 0)
{
sprintf(ssun.sun_path, "%s/%d",
"/var/spool/sockets/X11", display_number);
}
else
{
if (stat("/usr/spool/sockets/X11", &st) == 0)
{
sprintf(ssun.sun_path, "%s/%d",
"/usr/spool/sockets/X11", display_number);
}
else
{
struct utsname utsbuf;
/* HPSUX stores unix-domain sockets in
* /tmp/.X11-unix/`hostname`0
* instead of the normal /tmp/.X11-unix/X0.
*/
if (uname(&utsbuf) < 0)
fatal("uname: %.100s", strerror(errno));
sprintf(ssun.sun_path, "%.20s/%.64s%d",
X11_DIR, utsbuf.nodename, display_number);
}
}
}
#else /* HPSUX_NONSTANDARD_X11_KLUDGE */
{
struct stat st;

if (stat("/var/X", &st) == 0)
{
sprintf(ssun.sun_path, "%.80s/X%d",
"/var/X/.X11-unix", display_number);
}
else if (stat(X11_DIR, &st) == 0)
{
sprintf(ssun.sun_path, "%.80s/X%d",
X11_DIR, display_number);
}
else
{
sprintf(ssun.sun_path, "%.80s/X%d",
"/tmp/.X11-unix", display_number);
}
}
#endif /* HPSUX_NONSTANDARD_X11_KLUDGE */
if (connect(sock, (struct sockaddr *)&ssun,
AF_UNIX_SIZE(ssun)) < 0)
{
error("connect %.100s: %.100s",
ssun.sun_path, strerror(errno));
close(sock);
goto fail;
}

/* OK, we now have a connection to the display. */
goto success;
}

success:

/* We have successfully obtained a connection to
* the real X display.
*/

#if defined(O_NONBLOCK) && !defined(O_NONBLOCK_BROKEN)
(void)fcntl(sock, F_SETFL, O_NONBLOCK);
#else /* O_NONBLOCK && !O_NONBLOCK_BROKEN */
(void)fcntl(sock, F_SETFL, O_NDELAY);
#endif /* O_NONBLOCK && !O_NONBLOCK_BROKEN */
______________________________________________________

随后客户端用这个 socket 设置一个新通道。注意,如果客户端主机的本地没有终端显示器,在这一步,它也按自己
的环境变量 $DISPLAY 的值,打开一个 TCP socket 与远程 X服务器连接。

最后服务器把前面已经构造出的显示列表记录第一字段和客户端发送来的协议号与认证钥结合在一起构成一条显示记
录,置入用户的.Xauthority 文件中。并把 $DIAPLAY 环境变量的值设置为这条记录第一个字段的显示名。

做了这些之后,就可以进行 X 转发了。服务器运行 X程序时使用这个虚拟的 X 显示提交图形显示请求,把图形显示
数据写入这个虚拟的 X 显示,也即写入上面新建的通道发给客户端。客户端取得这些数据后再把它写入自己刚刚建立
的与 X 服务器连接的通道,也即向 X 服务器提交显示请求。

为什么客户端不直接把自己 .Xauthority 文件中一条显示配置记录交给服务器,由服务器按这条记录直接打开
TCPsocket 与客户端的 X 建立连接呢?ssh 的安全性也就在这里,如果这样做,就把等于把自己的 X 服务器完全奉送
给外界来使用,而 X 服务器本身又是问题多多的。前面伪造一个认证钥也是出于这个考虑,因为如果知道了认证钥,
显示记录里别的几个字段是很容易猜出的。

尽管做了这些,还是存在问题的。如果一个攻击者侵入或掌握着 ssh 服务器运行的主机,那么他/她发现一个 ssh连接
并进行 X 转发服务时,设法获取连接者的 $DISPLAY 环境变量值,再执行一下 "xauth value_of_$DISPLAY" 命令,就
得到显示记录了。随后他/她用 "xauth add" 命令把这条记录加入自己的 .Xauthority 文件中,再把自己的$DISPLAY环
境变量设置成这条记录的显示名。这样他/她就可以在 X转发连接期间运行 X 程序,X 程序的显示请求全部提交给客户
端的 X 服务器了。如果 X 服务器有什么漏洞的话,他/她可以自由运用了。
from http://fanqiang.chinaunix.net/app/other/2001-09-12/2836.shtml
---------------------------------------------------------------------------
概述 
许多网络程序,如telnet、rsh、rlogin或rexec,用明文(plain text)传送口令和秘密的信息,所以就可利用任何连接到网络上 的计算机监听这些程序和服务器之间的通信并获取口令和秘密信息。现在,telnet程序对于日常的管理工作是必不可少的,但是它又是不安全的,那么用什么 来替代它呢?OpenSSH就是那些过时的、不安全的远程登录程序,如:telnet、rlogin、rsh、rdist或rcp的替代品。 

在OpenSSH的README文件中提到:ssh(Secure Shell)程序可以通过网络登录到远程主机并执行命令。它提供了很强的安全验证可以在不安全的网络中进行安全的通信。 

我们把OpenSSH配置成支持TCP-Wrappers(inetd超级服务器),这样能够进一步地提高安全性而且也没有必要把OpenSSH 作为守护进程(daemon)在后台运行。当客户端的程序提出连接请求的时候,TCP-Wrappers守护进程就会在把连接重定向到OpenSSH之 前,对连接请求进行验证和授权。OpenSSH是自由软件而且使用不受专利保护的加密算法。因此,我建议你使用OpenSSH(免费而且修正了一些 bug),而不使用SSH1(免费但是有bug)和SSH2(现在使用商用的许可协议)。 

注意事项 
下面所有的命令都是Unix兼容的命令。 

源路径都为“/var/tmp”(当然在实际情况中也可以用其它路径)。 

安装在RedHat Linux 6.1和6.2下测试通过。 

要用“root”用户进行安装。 

OpenSSH的版本是1.2.3。 

软件包的来源 
OpenSSH的主页:http://violet.ibs.com.au/openssh/。 

下载:openssh-1.2.3.tar.gz。 

准备工作 
编译OpenSSH需要zlib-devel软件包,这个软件包包括头文件和函数库。编译使用zlib的压缩和解压函数的程序,就要事先安装这个软件包。可以用RedHat 6.1或6.2的光盘安装。 

l 用下面的命令验证一下在系统中是否已经安装了zlib-devel软件包: 

[root@deep /]# rpm -qi zlib-devel 

l 用下面命令在系统中安装zlib-devel软件包: 

[root@deep /]# mount /dev/cdrom /mnt/cdrom/ 
[root@deep /]# cd /mnt/cdrom/RedHat/RPMS/ 
[root@deep RPMS]# rpm -Uvh zlib-devel-version.i386.rpm 
gd ################################################## 
[root@deep RPMS]# rpm -Uvh gd-devel-version.i386.rpm 
zlib-devel ################################################## 
[root@deep RPMS]# cd /; umount /mnt/cdrom/ 

在使用OpenSSH之前,还必须安装OpenSSL。因为就算你不使用OpenSSL创建或保存加密文件,OpenSSH需要用OpenSSL的库文件才能正常运行。 

安装软件包需要注意的问题 
最好在编译前和编译后都做一张系统中所有文件的列表,然后用“diff”命令去比较它们,找出其中的差别并知道到底把软件安装在哪里。只要简单地在编译之 前运行一下命令“find /* >OpenSSH1”,在编译和安装完软件之后运行命令“find /* >  OpenSSH2”,最后用命令“diff OpenSSH1 OpenSSH2 > OpenSSH-Installed”找出变化。 

编译和安装 
把软件包(tar.gz)解压: 

[root@deep /]# cp openssh-version.tar.gz /var/tmp 
[root@deep /]# cd /var/tmp 
[root@deep tmp]# tar xzpf openssh-version.tar.gz 

编译和优化 
第一步 

转到OpenSSH的新目录下,先设置编译器的编译参数: 

CC="egcs" \ 
CFLAGS="-O9 -funroll-loops -ffast-math -malign-double -mcpu=pentiumpro -march=pentiumpro -fomit-frame- 
pointer -fno-exceptions" \ 
./configure \ 
--prefix=/usr \ 
--sysconfdir=/etc/ssh \ 
--with-tcp-wrappers \ 
--with-ipv4-default \ 
--with-ssl-dir=/usr/include/openssl 

这些设置告诉编译器如何编译OpenSSH: 

l 链接上libwrap函数库并且加上对TCP Wrappers的支持 

l 禁止Linux/glibc-2.1.2中域名解析的延时,缩短建立连接的时间 

l 设置OpenSSL函数库的路径,这样OpenSSH才能正常运行 

第二步 

现在,编译和安装OpenSSH: 

[root@deep openssh-1.2.3]# make 
[root@deep openssh-1.2.3]# make install 
[root@deep openssh-1.2.3]# make host-key 
[root@deep openssh-1.2.3]# install -m644 contrib/redhat/sshd.pam /etc/pam.d/sshd 

“make”命令把源文件编译成可执行的二进制文件,“make install”把二进制文件和配置文件安装在合适的目录下。“make host-key”生成主机密匙,“install”命令在RedHat Linux上安装对OpenSSH的PAM支持。 

清除不必要的文件 
用下面的命令删除不必要的文件: 

[root@deep /]# cd /var/tmp 
[root@deep tmp]# rm -rf openssh-version/ openssh-version.tar.gz 

“rm”命令删除所有编译和安装OpenSSH所需要的源程序,并且把OpenSSH软件的压缩包删除掉。 

配置 
可以到这去下载“floppy.tgz”文件:http://www.openna.com/books/floppy.tgz。把 “floppy.tgz”文件解开之后,可以在相应的目录下发现我们在这本书中介绍的所有软件的配置文件。这样就没有必要手工重新生成这些文件,或者用拷 贝粘贴的方法把它们粘贴到配置文件中去。不管是打算自己动手生成配置文件还是拷贝现成的,你都要学会自己修改配置文件并且把配置文件拷贝到正确的目录下。 下面将具体说明。 

为了运行OpenSSH,必须创建或者把下面的文件拷贝到相应的目录下: 

l 把“sshd_config”文件拷贝到“/etc/ssh”目录下 

l 把“ssh_config”文件拷贝到“/etc/ssh”目录下 

l 把“ssh”文件拷贝到“/etc/pam.d/”目录下 

可以把“floppy.tgz”解压之后,找到上面列出来的文件,并拷贝到合适的目录下,或者用拷贝粘贴的方法从本书中直接粘贴出。 

配置“/etc/ssh/ssh_config”文件 
“/etc/ssh/ssh_config”文件是OpenSSH系统范围的配置文件,允许你通过设置不同的选项来改变客户端程序的运行方式。这个文件的 每一行包含“关键词-值”的匹配,其中“关键词”是忽略大小写的。下面列出来的是最重要的关键词,用man命令查看帮助页(ssh (1))可以得到详细 的列表。 

编辑“ssh_config”文件(vi /etc/ssh/ssh_config),添加或改变下面的参数: 

# Site-wide defaults for various options 
Host * 
ForwardAgent no 
ForwardX11 no 
RhostsAuthentication no 
RhostsRSAAuthentication no 
RSAAuthentication yes 
PasswordAuthentication yes 
FallBackToRsh no 
UseRsh no 
BatchMode no 
CheckHostIP yes 
StrictHostKeyChecking no 
IdentityFile ~/.ssh/identity 
Port 22 
Cipher blowfish 
EscapeChar ~ 

下面逐行说明上面的选项设置: 

Host * 
选项“Host”只对能够匹配后面字串的计算机有效。“*”表示所有的计算机。 

ForwardAgent no 
“ForwardAgent”设置连接是否经过验证代理(如果存在)转发给远程计算机。 

ForwardX11 no 
“ForwardX11”设置X11连接是否被自动重定向到安全的通道和显示集(DISPLAY set)。 

RhostsAuthentication no 
“RhostsAuthentication”设置是否使用基于rhosts的安全验证。 

RhostsRSAAuthentication no 
“RhostsRSAAuthentication”设置是否使用用RSA算法的基于rhosts的安全验证。 

RSAAuthentication yes 
“RSAAuthentication”设置是否使用RSA算法进行安全验证。 

PasswordAuthentication yes 
“PasswordAuthentication”设置是否使用口令验证。 

FallBackToRsh no 
“FallBackToRsh”设置如果用ssh连接出现错误是否自动使用rsh。 

UseRsh no 
“UseRsh”设置是否在这台计算机上使用“rlogin/rsh”。 

BatchMode no 
“BatchMode”如果设为“yes”,passphrase/password(交互式输入口令)的提示将被禁止。当不能交互式输入口令的时候,这个选项对脚本文件和批处理任务十分有用。 

CheckHostIP yes 
“CheckHostIP”设置ssh是否查看连接到服务器的主机的IP地址以防止DNS欺骗。建议设置为“yes”。 

StrictHostKeyChecking no 
“StrictHostKeyChecking”如果设置成“yes”,ssh就不会自动把计算机的密匙加入“$HOME/.ssh/known_hosts”文件,并且一旦计算机的密匙发生了变化,就拒绝连接。 

IdentityFile ~/.ssh/identity 
“IdentityFile”设置从哪个文件读取用户的RSA安全验证标识。 

Port 22 
“Port”设置连接到远程主机的端口。 

Cipher blowfish 
“Cipher”设置加密用的密码。 

EscapeChar ~ 
“EscapeChar”设置escape字符。 

配置“/etc/ssh/sshd_config”文件 
“/etc/ssh/sshd_config”是OpenSSH的配置文件,允许设置选项改变这个daemon的运行。这个文件的每一行包含“关键词- 值”的匹配,其中“关键词”是忽略大小写的。下面列出来的是最重要的关键词,用man命令查看帮助页(sshd (8))可以得到详细的列表。 

编辑“sshd_config”文件(vi /etc/ssh/sshd_config),加入或改变下面的参数: 

# This is ssh server systemwide configuration file. 
Port 22 
ListenAddress 192.168.1.1 
HostKey /etc/ssh/ssh_host_key 
ServerKeyBits 1024 
LoginGraceTime 600 
KeyRegenerationInterval 3600 
PermitRootLogin no 
IgnoreRhosts yes 
IgnoreUserKnownHosts yes 
StrictModes yes 
X11Forwarding no 
PrintMotd yes 
SyslogFacility AUTH 
LogLevel INFO 
RhostsAuthentication no 
RhostsRSAAuthentication no 
RSAAuthentication yes 
PasswordAuthentication yes 
PermitEmptyPasswords no 
AllowUsers admin 

下面逐行说明上面的选项设置: 

Port 22 
“Port”设置sshd监听的端口号。 

ListenAddress 192.168.1.1 
“ListenAddress”设置sshd服务器绑定的IP地址。 

HostKey /etc/ssh/ssh_host_key 

“HostKey”设置包含计算机私人密匙的文件。 

ServerKeyBits 1024 
“ServerKeyBits”定义服务器密匙的位数。 

LoginGraceTime 600 
“LoginGraceTime”设置如果用户不能成功登录,在切断连接之前服务器需要等待的时间(以秒为单位)。 

KeyRegenerationInterval 3600 
“KeyRegenerationInterval”设置在多少秒之后自动重新生成服务器的密匙(如果使用密匙)。重新生成密匙是为了防止用盗用的密匙解密被截获的信息。 

PermitRootLogin no 
“PermitRootLogin”设置root能不能用ssh登录。这个选项一定不要设成“yes”。 

IgnoreRhosts yes 
“IgnoreRhosts”设置验证的时候是否使用“rhosts”和“shosts”文件。 

IgnoreUserKnownHosts yes 
“IgnoreUserKnownHosts”设置ssh daemon是否在进行RhostsRSAAuthentication安全验证的时候忽略用户的“$HOME/.ssh/known_hosts” 

StrictModes yes 
“StrictModes”设置ssh在接收登录请求之前是否检查用户家目录和rhosts文件的权限和所有权。这通常是必要的,因为新手经常会把自己的目录和文件设成任何人都有写权限。 

X11Forwarding no 
“X11Forwarding”设置是否允许X11转发。 

PrintMotd yes 
“PrintMotd”设置sshd是否在用户登录的时候显示“/etc/motd”中的信息。 

SyslogFacility AUTH 
“SyslogFacility”设置在记录来自sshd的消息的时候,是否给出“facility code”。 

LogLevel INFO 
“LogLevel”设置记录sshd日志消息的层次。INFO是一个好的选择。查看sshd的man帮助页,已获取更多的信息。 

RhostsAuthentication no 
“RhostsAuthentication”设置只用rhosts或“/etc/hosts.equiv”进行安全验证是否已经足够了。 

RhostsRSAAuthentication no 
“RhostsRSA”设置是否允许用rhosts或“/etc/hosts.equiv”加上RSA进行安全验证。 

RSAAuthentication yes 
“RSAAuthentication”设置是否允许只有RSA安全验证。 

PasswordAuthentication yes 
“PasswordAuthentication”设置是否允许口令验证。 

PermitEmptyPasswords no 
“PermitEmptyPasswords”设置是否允许用口令为空的帐号登录。 

AllowUsers admin 
“AllowUsers”的后面可以跟着任意的数量的用户名的匹配串(patterns)或user@host这样的匹配串,这些字符串用空格隔开。主机名可以是DNS名或IP地址。 

配置OpenSSH使其使用TCP-Wrappers inetd超级服务器 
TCP-WRAPPERS用来启动和停止sshd1服务。当inetd运行的时候,它会从配置文件(默认为“/etc/inetd.conf”)中读入配置信息。在配置文件中每一行的不同项是用TAB或空格分开。 

第一步 

编辑“inetd.conf”文件(vi /etc/inetd.conf)并加入这一行: 

ssh stream tcp nowait root /usr/sbin/tcpd sshd –i 

注意:“-i”参数很重要,它说明sshd是被inetd运行的。在加入这一行后,通过发送一个SIGHUP信号(killall –HUP inetd)来更新“inetd.conf”文件。 

[root@deep /root]# killall -HUP inetd 

第二步 

编辑“hosts.allow”文件(vi /etc/hosts.allow)并加入这一行: 

sshd: 192.168.1.4 win.openarch.com 

这一行表示IP地址为“192.168.1.4”,主机名为“win.openarch.com”的计算机允许用ssh访问服务器。 

下面这些“daemon”字符串(用于TCP-WRAPPERS)被sshd1使用: 

sshdfwd-X11 (允许/禁止X11转发). 
sshdfwd- (TCP转发). 
sshdfwd- (port-name在/etc/services中定义。用于TCP转发). 

注意:如果准备使用ssh,一定要用在所有的服务器上。如果十台安全的服务器和一台不安全的服务器配在一起,也谈不上什么安全性。 

更多的资料 
如果想查找详细的资料可以用man命令查帮助页,读取相关信息: 

$ man ssh (1) - OpenSSH secure shell client (remote login program) 
$ man ssh [slogin] (1) - OpenSSH secure shell client (remote login program) 
$ man ssh-add (1) - adds identities for the authentication agent 
$ man ssh-agent (1) - authentication agent 
$ man ssh-keygen (1) - authentication key generation 
$ man sshd (8) - secure shell daemon 

SSH1每用户配置 
第一步 

为本地服务器创建私有和公用密匙,执行下面的命令: 

[root@deep]# su username 
[username@deep]$ ssh-keygen1 

举个例子,显示出来的结果可能是: 

Initializing random number generator... 
Generating p: ............................++ (distance 430) 
Generating q: ......................++ (distance 456) 
Computing the keys... 
Testing the keys... 
Key generation complete. 
Enter file in which to save the key (/home/username/.ssh/identity): 【按下回车键】 
Enter passphrase: 
Enter the same passphrase again: 
Your identification has been saved in /home/username/.ssh/identity. 
Your public key is: 
1024 37 
14937757511251955533691120318477293862290049394715136511145806108870001764378494676831 
29757784315853227236120610062314604405364871843677484233240919418480988907860997175244 
46977589647127757030728779973708569993017043141563536333068888944038178461608592483844 
590202154102756903055846534063365635584899765402181 username@deep.openarch.com 
Your public key has been saved in /home/username/.ssh/identity.pub 

注意:如果有多个帐号需要为每个帐号创建一个密匙。 

你可能要为下面的服务器创建密匙: 

l Mail服务器 

l Web服务器 

l 网关服务器 

这允许对这些服务器进行有限的访问,例如,不允许用Mail服务器的帐号访问Web服务器或网关服务器。这样可以增加整体的安全性,即使因为某种原因有一个密匙被泄密了,也不会影响到其它的服务器。 

第二步 

把本机的公用密匙(identity.pub)拷贝到远程主机的“/home/username/.ssh”目录下,例如,使用“authorized_keys”这个名字。 

注意:拷贝文件的一个方法使用ftp命令,另一个办法是把公用密匙用email(包含“~/.ssh/identity.pub”文件的内容)发给系统管理员。 

改变pass-phrase 

用加上“-p”参数的“ssh-keygen”命令,在任何时候都可以改变pass-phrase。用下面的命令,改变pass-phrase: 

[root@deep]# su username 
[username@deep]$ ssh-keygen1 –p 

Enter file key is in (/home/username/.ssh/identity): [按下回车键] 
Enter old passphrase: 
Key has comment username@deep.openarch.com 
Enter new passphrase: 
Enter the same passphrase again: 
Your identification has been saved with the new passphrase. 

OpenSSH用户工具 
下面列出的是一些我们经常要用到的命令,当然还有很多其它的命令,更详细的信息可以查看man帮助页或其它文档。 

ssh 
ssh(Secure Shell)是用来登录远程计算机和在远程计算机上执行命令的程序。它是用来替代rlogin和rsh,以及在不安全的网络环境下在两台计算机之间提供安全和加密的信息交流。X11连接和TCP/IP端口可以被转发到一个安全的通道里。 

用下面的命令,登录远程计算机: 

[root@deep]# ssh 

例如: 

[root@deep]# ssh username www.openarch.com 
username@deep.openarch.com’s password: 
Last login: Tue Oct 19 1999 18:13:00 -0400 from gate.openarch.com 
Welcome to www.openarch.com on Deepforest. 

是用来登录ssh服务器的用户名,是ssh服务器主机的地址。 

scp 
可以用这个命令把文件从本地计算机拷贝到远程计算机,或者反之,甚至可以在两台远程计算机之间用“scp”命令拷贝文件。把远程主机上的文件拷贝到当前目录的一个简单的方法如下。 

用下面的命令把文件从远程主机拷贝到本地主机上: 

[root@deep /]# su admin 
[admin@deep /]$ scp -p :/dir/for/file localdir/to/filelocation 

例如: 

[username@deep]$ scp -p username@mail:/etc/test1 /tmp 
Enter passphrase for RSA key username@mail.openarch.com: 
test1 | 2 KB | 2.0 kB/s | ETA: 00:00:00 | 100% 

用下面的命令把文件从本地主机拷贝到远程主机上: 

[root@deep /]# su admin 
[admin@deep /]$ scp -p localdir/to/filelocation :/dir/for/file 

例如: 

[username@deep]$ scp -p /usr/bin/test2 username@mail:/var/tmp 
username@mails password: 
test2 | 7 KB | 7.9 kB/s | ETA: 00:00:00 | 100% 

注意:“-p”选项表示文件的改变和访问时间属性以及权限,在拷贝过程中被保留。通常是需要这样的。 

安装到系统中的文件 
> /etc/ssh 
> /etc/ssh/ssh_config 
> /etc/ssh/sshd_config 
> /etc/ssh_host_key 
> /etc/ssh_host_key.pub 
> /usr/bin/ssh 
> /usr/bin/slogin 
> /usr/man/man1/ssh.1 
> /usr/man/man1/scp.1 
> /usr/man/man1/ssh-add.1 
> /usr/man/man1/ssh-agent.1 
> /usr/man/man1/ssh-keygen.1 
> /usr/bin/scp 
> /usr/bin/ssh-add 
> /usr/bin/ssh-agent 
> /usr/bin/ssh-keygen 
> /usr/man/man1/slogin.1 
> /usr/man/man8/sshd.8 
> /usr/sbin/sshd 

Windows平台上免费的SSH客户软件 
Putty 
Putty的主页:http://www.chiark.greenend.org.uk/~sgtatham/putty.html 

Tera Term Pro and TTSSH 
Tera Term Pro的主页:http://hp.vector.co.jp/authors/VA002416/teraterm.html 

TTSSH Homepage:http://www.zip.com.au/~roca/download.html 

版权说明 
这篇文章翻译和改编自Gerhard Mourani的《Securing and Optimizing Linux: RedHat Edition》,原文及其版权协议请参考:www.openna.com。 

中文版的版权属于作者brimmer和www.linuxaid.com.cn。
from http://fanqiang.chinaunix.net/app/ssl/2001-04-19/2671.shtml
-----------------------------------------------------------------------------------------------------------

如何在centos/fedora/redhat Linux 上安装、使用 SSH2

软件取得

1 RedHat 6.2

http://freesoft.online.sh.cn/

2 SSH2 Server

rpm : ssh-commercial-server-2.2.0-2nox.i386.rpm
source: ssh-2.2.0.tar.gz

http://www.ssh.com

3 SSH2 Client
rpm : ssh-commercial-workstation-2.2.0-2.i386.rpm
http://www.ssh.com


三、软件安装

说明:Remote Host Name :Remote (Server) 192.168.1.222
Local Host Name :Local (Client) 192.168.1.223

1 安装 Redhat6.2

2 安装 SSH2 Server(Remote Host)

使用 RPM
[root@Remote root]# rpm -ivh ssh-commercial-server-2.2.0-2nox.i386.rpm

使用 SOURCE

[root@Remote root]# tar xzvf ssh-2.2.0.tar.gz
# cd ssh-2.2.0
# ./configure
# make
# make install


3 安装 SSH2 Clinet(Local Host)

[root@Local root]# rpm -ivh ssh-commercial-workstation-2.2.0-2.i386.rpm



四、系统配置
1.在 Remote Host 启动sshd
[root@Remote root]/usr/loca/sbin/sshd2

2 在 Local Host 添加用户账号 如 bill
[root@Local root] useradd bill
[root@Local root] passwd bill

3 在Client 上建立用户的公共和私人密钥
以bill登陆到 Local Host 上
[bill@Local local]$ ssh-keygen
Generating 1024-bit dsa key pair
9 o.oOo..oOo.o
Key generated.
1024-bit dsa, created by bill@Local Wed Sep 23 07:11:02 1998
Passphrase :输入一些字符,不超过20个
Again :重复输入一遍
Private key saved to /home/bill/.ssh2/id_dsa_1024_a

4 在Client 上建立用户的认证文件
以bill登陆到 Local Host 上
[bill@Local local]$cd ~/.ssh2
[bill@Local local]$echo "IdKey id_dsa_1024_a" > identification

4. 在 Remote Host 添加用于远程登陆的用户账号 如 bill
[root@Remote root]# useradd bill
[root@Remote root]# passwd bill

5. 以bill登陆到 Remote Host 上
[bill@Remote local]$ ssh-keygen
Generating 1024-bit dsa key pair
9 o.oOo..oOo.o
Key generated.
1024-bit dsa, created by bill@Local Wed Sep 23 07:11:02 1998
Passphrase :输入一些字符,不超过20个
Again :重复输入一遍
Private key saved to /home/bill/.ssh2/id_dsa_1024_a

6. 以bill登陆到 Local Host
[bill@Local local]$ cd ~
[bill@Local local]$ cp ./.ssh2/id_dsa_1024_a.pub Local.pub

以bill ftp Remote Host
[bill@local bill]$ ftp local

ftp> lcd ~/.ssh2
ftp> cd ~/.ssh2
ftp> put Local.pub
ftp> bye

以bill Telnet Remote Host
[bill@local bill]$ telnet local
[bill@remote bill]$ cd ~/.ssh2
[bill@remote .ssh2]$echo "Key Local.pub" > authorization


五 测试
在Local Host

[bill@local bill]$ ssh Remote
Passphrase for key "/home/bill/.ssh2/id_dsa_1024_a" with comment "1024-bit d: 输入前面输入的一些字符
Authentication successful.

[bill@Remote bill]$ netstat -n
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 252 192.168.1.222:22 192.168.1.223:3532 ESTABLISHED
Active UNIX domain sockets (w/o servers)
Proto RefCnt Flags Type State I-Node Path
unix 9 [ ] DGRAM 436 /dev/log
unix 0 [ ] STREAM CONNECTED 177 @00000016
unix 0 [ ] DGRAM 771
unix 0 [ ] DGRAM 753
unix 0 [ ] DGRAM 672
unix 0 [ ] DGRAM 636
unix 0 [ ] DGRAM 590
unix 0 [ ] DGRAM 575
unix 0 [ ] DGRAM 523
unix 0 [ ] DGRAM 458
unix 0 [ ] DGRAM 446

[bill@local bill]$ sftp Remote
Passphrase for key "/home/bill/.ssh2/id_dsa_1024_a" with comment "1024-bit d:
sftp> ls -l
drwxr-xr-x 5 bill bill 4096 Jul 12 6:29 Desktop/
-rwxr-xr-x 1 bill bill 333 Jul 12 6:29 .emacs*
-rw-r--r-- 1 bill bill 24 Jul 12 6:29 .bash_logout
-rw-r--r-- 1 bill bill 230 Jul 12 6:29 .bash_profile
-rw-r--r-- 1 bill bill 124 Jul 12 6:29 .bashrc
drwxr-xr-x 3 bill bill 4096 Jul 12 6:29 .kde/
-rw-r--r-- 1 bill bill 435 Jul 12 6:29 .kderc
-rw-r--r-- 1 bill bill 3394 Jul 12 6:29 .screenrc
-rw------- 1 bill bill 316 Jul 12 16:31 .bash_history
drwxr-xr-x 3 bill bill 4096 Jul 12 16:00 .ssh2/
sftp>

from http://fanqiang.chinaunix.net/app/other/2001-05-10/2717.shtml
-------------------------------------------------------------------------------------------------------------------

远程连接(telnet/ftp/rsh/ssh)作为root的用法和总结

一:简介

      虽然目前大家都认为telnet/ftp/rsh作为不安全的服务已经不太使用,但在局域网内部
      的某些情况下仍然广泛地被使用,特别是安全性不是很重要的场合下,某些服务如FTP,
      由于历史较长,至今大多数场合仍然大有用处。很多人在使用这些服务直接登录作为root
      时遇到问题,本文就简单地介绍一下设置方法和相关问题。

      二:环境

      假设本文的所有操作环境是Redhat Linux,一台为telnet/ftp/rsh/ssh客户,IP为
      192.168.0.2,主机名为
      client.domain.com;另一台为服务器,IP为192.168.0.1,主机名为
      server.domain.com,两者都运行redhat linux 7.1 .

      三:用法

      1. 直接telnet作为root.

      a. 在服务器server.domain.com上运行/usr/sbin/ntsysv后选中telnet服务,击OK。

      b. 运行#/sbin/service xinetd restart 启动telnet服务

      c. 运行#echo "pts/0" >> /etc/securetty 和
      #echo "pts/1" >> /etc/securetty
      ......
      更多的远程终端允许直接登录作为root

      d. 确保在server.domain.com上的/etc/hosts中有类似下面的行。
      192.168.1.2 client.domain.com client

      如果没有,则在server上运行echo "192.168.1.2 client.domain.com client" >>
      /etc/hosts

      至此你应该能从client远程telnet直接作为root了。

      如果服务器是redhat 6.x,则加单个数字如0,1,2,3...到/etc/securetty后面,一个数
      字一行,必须以0开始。

      仅仅加数字而己,没有pts,tty。

      如果服务器是redhat 5.x,则加ttyp0, ttyp1,ttyp2... 等到/etc/securetty.

      经常有人问,为什么telnet/ftp进服务器时需要等很久?那是因为当服务器检测出有客户
      远程连接进来时,它知道客户的IP,但根据telnet/ftp服务的内部机制,它需要反向检
      查该IP的域名,如果你有DNS服务器且设置了反向域名,则很快查到,若没有,则简单地
      在服务器的/etc/hosts中加入客户的记录就可以了。

      2. 直接rsh作为root.

      a. 在服务器上运行/urs/bin/ntsysv选中rexec ,rlogin ,rsh三项服务。

      b. 运行#/sbin/service xinetd restart 启动该三项服务。

      c. 运行#echo "rexec" >> /etc/securetty;echo "rlogin" >>
      /etc/securetty;echo "rsh" >> /etc/securetty

      d. 在服务器上运行#echo "192.168.0.2 root" >> /root/.rhosts
      或者 #echo "client root" >> /root/.rhosts且确保在服务器上的/etc/hosts中有
      client的记录
      192.168.0.2 client.domain.com client

      至此你应该可以从client直接以root身份rsh到服务器不需密码了。

      注: 仅仅redhat 7.x 开始需要为rsh设置/etc/securetty.

      3. 直接ftp作为root.

      这个比较简单,就是在server上的/etc/ftpusers中的root一行前面放个注释#即可。

      在现代的网络技术下,telnet/rsh/ftp都可以被ssh/scp代替了,甚至已经有了一个
      winscp,图形化的SCP工具,在http://winscp.vse.cz/eng/ , 免费的windows ssh客
      户有许多,象tera term , putty等等。
      不过,FTP在某些场合仍然有它的用处。下面例举两种:

      a. FTP可以直接把远端服务器上某个目录压缩后传送到客户端,如远程服务器有sbin目
      录,可以用get sbin.tar.gz直接把整个目录压缩后FTP下来成为单个压缩文件。这个方
      式可以很好地用在远程复制整个
      linux OS。

      b. 为了远程复制另一台linux OS,可以用redhat 光盘启动到准备进行分区的界面(选择
      自动还是手动分区的界面),然后用ALT+F2切换到第二个终端,设置网卡的IP和默认网关,
      用fdisk/e2fsck 分区用格式化本地硬盘,用FTP远程得到服务器的所有目录除了proc目
      录,然后即可以复制一台与远端一样的服务器。

      详细做法请参考《文章荟萃》中另一篇文章
      http://www.linuxforum.net/doc/cp-wu.html 《如何远程复制另一台Linux服务器及
      相关问题
      》。

      4. 直接ssh作为root.

      OpenSSH的默认设置sshd_config是允许登录作为root的 PermitRootLogin yes ,你可
      以改为no去禁止这个功能增强安全性。
      为了直接不用密码登录作为root,最好是采用RSA键对认证方式进行。

      可参考《文章荟萃》中另一篇文章
      http://www.linuxforum.net/doc/ossh-wu.html
      《如何在两台linux服务器之间用RSA键对的方法SSH/SCP不需密码》
from http://fanqiang.chinaunix.net/system/other/2001-09-02/856.shtml

-----------------------------------------------

ssh keygen 免输入密码,登录ssh

懒得打密码, 以 key 做认证登录.
步骤如下:
• ssh-keygen -t rsa 或 ssh-keygen -d (dsa) => 产生出 id_rsa, id_rsa.pub
• scp id_rsa.pub server_hostname:~/.ssh/
• ssh server_hostname
• cat .ssh/id_rsa.pub >> .ssh/authorized_keys 即可(chmod 600 authorized_keys)
• 这样子就可以 key 认证登入, 不需输入密码.
PS:
gen 时会问 Enter passphrase (empty for no passphrase):
此处直接 enter 跳过,下次才不会询问password
简单解说一下:
id_rsa: private key
id_rsa.pub: public key
将 public key(id_rsa.pub) 拷贝到远程的计算机后, 加到那 user 的 .ssh/authorized_keys 中.
之后联机时, 就会用本机的 private key(id_rsa) 与远程计算机的 public key(authorized_keys) 做认证, 确认完成就可以直接登入, 不需输入账号密码, 而且也比较安全.
--------------------------------------------------------------------------------------------------------------------------------------------
此教程目的就是屏蔽通过密码登录SSH,而仅使用密匙登录SSH
这样可以大大提高VPS的安全性(程序漏洞除外)
注意:本例本地环境为linux系统,WIN系统下可参考网络上其他教程
警告:下面的操作有风险,可能导致你无法SSH连接管理你的VPS,建议有VPS操控面板,能在线重装系统的用户尝试,HyperVM 面板里有个默认的帐号密码SSH连接母机后可以跳转至root用户SSH连入你的VPS。

测试环境:本地ubuntu,远程VPS为centos系统

ubuntu系统禁止直接用root用户登录,我这里举例一个用户名 test
这个 test 用户是你在安装 ubuntu系统过程中创建的
它有 sudo 的权限(以后 useradd 的用户默认是没有sudo权限的)
第一步,SSH密码形式登录远地VPS,然后进行下列设置:
引用:
1.添加一个用户 test 并指定密码
# useradd test
# passwd test
2.给 test用户赋予sudo 权限
# usermod -G wheel test (添加test用户至wheel用户组)
# vi /etc/pam.d/su  (修改配置文件,找到# auth required /lib/security/$ISA/pam_wheel.so use_uid 去掉行首的“#”)
# echo “SU_WHEEL_ONLY yes” >> /etc/login.defs (仅wheel用户组可以使用sudo)
3.切换test用户登录
# su – test
4.在test用户状态下创建密匙对
# ssh-keygen -t rsa  (保存至默认路径/home/test/.ssh/id_rsa,并指定密码)
$ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys (公匙文件拷贝成系统默认调用的文件名)
$ chmod 400 ~/.ssh/authorized_keys (修改权限)
5.切换root用户修改SSH配置文件
$ su
# vi /etc/ssh/sshd_config
(找到#Protocol 2,1 去掉行首“#”,再将行末的“,1”删除,仅使用SSH2方式连接;找到#ServerKeyBits 768去掉行首“#”,并将768改为1024,加强密码强度;找到#PermitRootLogin yes去掉行首“#”,并将yes改为no禁止用root进行登录;找到#PasswordAuthentication yes去掉行首“#”,将yes改为no不允许密码方式的登录;找到#PermitEmptyPasswords no去掉行首的“#”,禁止空密码登录)
6.重启SSH服务
# /etc/rc.d/init.d/sshd restart
第二步,本地环境登录SHEEL创建密匙保存目录
引用:
$ cd ~ (进入 test用户家目录)
$ mkdir .ssh (建立文件夹)
第三步,把VPS上的密匙 id_rsa 保存在 ~/.ssh/ 目录里(建议用SFTP加密下载)
登录后 su 切换成 root 搞定,收工。
第一次登录的时候会提示公匙改变,yes保存新公匙到本地就可以了。
以后登录直接使用命令  ssh IP 就可以了,不象以前得输入 ssh IP -l root
PS:当然你在本地创建密匙对,然后把公匙传到VPS  /home/test/.ssh/ 目录下,也是一样的。
PS:VPS公匙保存在相同目录下known_hosts文件中,如果碰到公匙改变,可以直接覆盖,或者手动删除后再次访问VPS加载。
FROM: http://www.pihai.net/technology/managed_vps_by_ssh_keys_under_the_linux_system.html
---------------------------------------------------------------------------------------------------------------
出于安全的考虑,我的服务器SSH远程认证去掉了通过用户名+密码模式的认证机制。转而使用Windows下的Puttygen生成的 Key(以.ppk结尾)来验证登录,同时为了增强安全性,把SSH的端口配到了高端端口上。然而转到Mac平台下去之后,因其本身就带有 Shell(Mac是基于FreeBSD进行的包装),所以本身也就有了SSH,用不上Putty了,但是因此所导致的问题是,我在Windows下的 Key到了Mac平台上也就用不上了,在这种情况下,迫不得已,就只有去找转变认证机制的方法。
出于思维的习惯(人类避重就轻的惰性),一开始考虑的是把服务器改回使用用户名加密码的认证机制,但显然这不是一个明智的做法。于是就把眼光转向了 转换ppk key的方向,基于这个想法,再想到解铃还得系铃人,所以目光自然又重新定位回了Putty这个开源的东东,下载下源码一读,发现它对Uninx的支持也 还是很好的。那好,我只需要一个puttygen,编译无非是一点体力活。
以下是全过程:
1、下载Putty 0.6源代码并编译:
  1. wget http://putty.very.rulez.org/latest/putty-0.60.tar.gz
  2. tar xzvf putty-0.60.tar.gz
  3. cd putty-0.60
  4. configureprefix=/opt/iApps/putty
  5. make
嗯,不用讶异,接下来没有make install的过程,因为我们不需要真的把Putty安装到/opt/iApps/putty里,当你在Make的时候,Puttygen已经编译完 成,这里在Configure写上一个prefix路径,只是想提醒你,如果想安装的话,最好指定一个目录,以便于管理。
那么接下来转换我们Windows下的Putty key:
  1. putty-0.60/unix/puttygen my_ssh_key.ppk -O private-openssh -o my_openssh_key.ssh
顺利的生成my_openssh_key.ssh文件,此时就可以通过以下命令来进行登录了:
  1. ssh root@172.16.1.99 -i my_openssh_key.ssh -p 9999
FROM: http://www.handaoliang.com/article_106.html
-------------------------------------------------
SSH相关配置文件的修改
首先修改SSH的配置文件。如下:
[root@sample ~]# vi /etc/ssh/sshd_config  ← 用vi打开SSH的配置文件
#Port 22 ← 找到此行将行头“#”删除,再将行末的“22”改成其他端口,默认22不安全
#Protocol 2,1 ← 找到此行将行头“#”删除,再将行末的“,1”删除,只允许SSH2方式的连接
Protocol 2 ← 修改后变为此状态,仅使用SSH2
#ServerKeyBits 768 ← 找到这一行,将行首的“#”去掉,并将768改为1024
ServerKeyBits 1024 ← 修改后变为此状态,将ServerKey强度改为1024比特
#PermitRootLogin yes  ← 找到这一行,将行首的“#”去掉,并将yes改为no
PermitRootLogin no  ← 修改后变为此状态,不允许用root进行登录
#PasswordAuthentication yes ← 找到这一行,将yes改为no
PasswordAuthentication no ← 修改后变为此状态,不允许密码方式的登录
#PermitEmptyPasswords no  ← 找到此行将行头的“#”删除,不允许空密码登录
PermitEmptyPasswords no  ← 修改后变为此状态,禁止空密码进行登录
然后保存并退出。(vi保存退出的命令为ZZ)
因为我们只想让SSH服务为管理系统提供方便,所以在不通过外网远程管理系统的情况下,只允许内网客户端通过SSH登录到服务器,以最大限度减少不安全因素。设置方法如下:
[root@sample ~]# vi /etc/hosts.deny  ← 修改屏蔽规则,在文尾添加相应行
#
# hosts.deny This file describes the names of the hosts which are
# *not* allowed to use the local INET services, as decided
# by the ‘/usr/sbin/tcpd’ server.
#
# The portmap line is redundant, but it is left to remind you that
# the new secure portmap uses hosts.deny and hosts.allow. In particular
# you should know that NFS uses portmap!
sshd: ALL  ← 添加这一行,屏蔽来自所有的SSH连接请求
[root@sample ~]# vi /etc/hosts.allow  ← 修改允许规则,在文尾添加相应行
#
# hosts.allow This file describes the names of the hosts which are
# allowed to use the local INET services, as decided
# by the ‘/usr/sbin/tcpd’ server.
#
sshd: 192.168.0.  ← 添加这一行,只允许来自内网的SSH连接请求
重新启动SSH服务
在修改完SSH的配置文件后,需要重新启动SSH服务才能使新的设置生效。
[root@sample ~]# /etc/rc.d/init.d/sshd restart  ← 重新启动SSH服务器
Stopping sshd:             [ OK ]
Starting sshd:             [ OK ]  ← SSH服务器重新启动成功
这时,在远程终端(自用PC等等)上,用 SSH客户端软件以正常的密码的方式是无法登录服务器的。为了在客户能够登录到服务器,我们接下来建立SSH用的公钥与私钥,以用于客户端以“钥匙”的方式登录SSH服务器。
SSH2的公钥与私钥的建立
登录为一个一般用户,基于这个用户建立公钥与私钥。(这里以 centospub用户为例)
[root@sample ~]# su – centospub ← 登录为一般用户centospub
[centospub@sample ~]$ ssh-keygen -t rsa  ← 建立公钥与私钥
Generating public/private rsa key pair.
Enter file in which to save the key (/home/kaz/.ssh/id_rsa):  ← 钥匙的文件名,这里保持默认直接回车
Created directory ‘/home/kaz/.ssh’
Enter passphrase (empty for no passphrase):  ← 输入口令
Enter same passphrase again:   ← 再次输入口令
Your identification has been saved in /home/kaz/.ssh/id_rsa.
Your public key has been saved in /home/kaz/.ssh/id_rsa.pub.
The key fingerprint is:
tf:rs:e3:7s:28:59:5s:93:fe:33:84:01:cj:65:3b:8e centospub@sample.centospub.com
然后确认一下公钥与密钥的建立,以及对应于客户端的一些处理。
[centospub@sample ~]$ cd ~/.ssh  ← 进入用户SSH配置文件的目录
[centospub@sample .ssh]$ ls -l  ← 列出文件
total 16
-rw——- 1 centospub centospub 951 Sep 4 19:22 id_rsa  ← 确认私钥已被建立
-rw-r–r– 1 centospub centospub 241 Sep 4 19:22 id_rsa.pub  ← 确认公钥已被建立
[centospub@sample .ssh]$ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys  ← 公钥内容输出到相应文件中
[centospub@sample .ssh]$ rm -f ~/.ssh/id_rsa.pub  ← 删除原来的公钥文件
[centospub@sample .ssh]$ chmod 400 ~/.ssh/authorized_keys  ← 将新建立的公钥文件属性设置为400
然后,将私钥通过安全的方式转移到欲通过SSH连接到服务器的PC上。(如 Putty 等软件转换私匙,即可用私匙登陆)
首先修改SSH的配置文件。如下:
[root@sample ~]# vi /etc/ssh/sshd_config  ← 用vi打开SSH的配置文件
#Port 22 ← 找到此行将行头“#”删除,再将行末的“22”改成其他端口,默认22不安全
#Protocol 2,1 ← 找到此行将行头“#”删除,再将行末的“,1”删除,只允许SSH2方式的连接
Protocol 2 ← 修改后变为此状态,仅使用SSH2
#ServerKeyBits 768 ← 找到这一行,将行首的“#”去掉,并将768改为1024
ServerKeyBits 1024 ← 修改后变为此状态,将ServerKey强度改为1024比特
#PermitRootLogin yes  ← 找到这一行,将行首的“#”去掉,并将yes改为no
PermitRootLogin no  ← 修改后变为此状态,不允许用root进行登录
#PasswordAuthentication yes ← 找到这一行,将yes改为no
PasswordAuthentication no ← 修改后变为此状态,不允许密码方式的登录
#PermitEmptyPasswords no  ← 找到此行将行头的“#”删除,不允许空密码登录
PermitEmptyPasswords no  ← 修改后变为此状态,禁止空密码进行登录
然后保存并退出。(vi保存退出的命令为ZZ)
因为我们只想让SSH服务为管理系统提供方便,所以在不通过外网远程管理系统的情况下,只允许内网客户端通过SSH登录到服务器,以最大限度减少不安全因素。设置方法如下:
[root@sample ~]# vi /etc/hosts.deny  ← 修改屏蔽规则,在文尾添加相应行
## hosts.deny This file describes the names of the hosts which are# *not* allowed to use the local INET services, as decided# by the ‘/usr/sbin/tcpd’ server.## The portmap line is redundant, but it is left to remind you that# the new secure portmap uses hosts.deny and hosts.allow. In particular# you should know that NFS uses portmap!
sshd: ALL  ← 添加这一行,屏蔽来自所有的SSH连接请求
[root@sample ~]# vi /etc/hosts.allow  ← 修改允许规则,在文尾添加相应行
## hosts.allow This file describes the names of the hosts which are# allowed to use the local INET services, as decided# by the ‘/usr/sbin/tcpd’ server.#sshd: 192.168.0.  ← 添加这一行,只允许来自内网的SSH连接请求
重新启动SSH服务
在修改完SSH的配置文件后,需要重新启动SSH服务才能使新的设置生效。
[root@sample ~]# /etc/rc.d/init.d/sshd restart  ← 重新启动SSH服务器
Stopping sshd:             [ OK ]Starting sshd:             [ OK ]  ← SSH服务器重新启动成功
这时,在远程终端(自用PC等等)上,用 SSH客户端软件以正常的密码的方式是无法登录服务器的。为了在客户能够登录到服务器,我们接下来建立SSH用的公钥与私钥,以用于客户端以“钥匙”的方式登录SSH服务器。
SSH2的公钥与私钥的建立
登录为一个一般用户,基于这个用户建立公钥与私钥。(这里以 centospub用户为例)
[root@sample ~]# su – centospub ← 登录为一般用户centospub
[centospub@sample ~]$ ssh-keygen -t rsa  ← 建立公钥与私钥Generating public/private rsa key pair.Enter file in which to save the key (/home/kaz/.ssh/id_rsa):  ← 钥匙的文件名,这里保持默认直接回车Created directory ‘/home/kaz/.ssh’Enter passphrase (empty for no passphrase):  ← 输入口令Enter same passphrase again:   ← 再次输入口令Your identification has been saved in /home/kaz/.ssh/id_rsa.Your public key has been saved in /home/kaz/.ssh/id_rsa.pub.The key fingerprint is:tf:rs:e3:7s:28:59:5s:93:fe:33:84:01:cj:65:3b:8e centospub@sample.centospub.com
然后确认一下公钥与密钥的建立,以及对应于客户端的一些处理。
[centospub@sample ~]$ cd ~/.ssh  ← 进入用户SSH配置文件的目录
[centospub@sample .ssh]$ ls -l  ← 列出文件total 16-rw——- 1 centospub centospub 951 Sep 4 19:22 id_rsa  ← 确认私钥已被建立-rw-r–r– 1 centospub centospub 241 Sep 4 19:22 id_rsa.pub  ← 确认公钥已被建立
[centospub@sample .ssh]$ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys  ← 公钥内容输出到相应文件中
[centospub@sample .ssh]$ rm -f ~/.ssh/id_rsa.pub  ← 删除原来的公钥文件
[centospub@sample .ssh]$ chmod 400 ~/.ssh/authorized_keys  ← 将新建立的公钥文件属性设置为400
然后,将私钥通过安全的方式转移到欲通过SSH连接到服务器的PC上。(如 Putty 等软件转换私匙,即可用私匙登陆)
 ------------------------------------------------------------------------------------------------------
用ssh转移数据
Linux 的加密拷贝命令scp, 于是问题就简单了:
# scp -rp dir-to-copy user@domain:/path-to-copy-to
这么一条命令就解决了,而且数据是在一条安全的遂道里传输。由于资料较多,传输过程比较漫长,为了这段时间“妞照泡舞照跳”,我们需要让拷贝去后台 执行。
于是按 Ctrl+z 把程序扔到后台去,再输入 bg %1 让它在后台继续执行。
然后该干吗干吗去,一早起来就会发现那一大坨东西已经乖乖的呆在新的地方了。from:
http://bemike.org/posts/248
----------------------------------------------------------------------------------------------------------
SSH Tunnel扫盲
SSH Tunnel有三种,分别是本地Local(ssh -NfL),远程Remote(ssh -NfR),动态Dynamic(ssh -NfD)。(含义参考man ssh

说明:在我们举例说明用法之前,先假设你有一台机器,它的IP是a.b.c.d。

1:本地Local(ssh -NfL)

ssh -NfL a.b.c.d:1234:www.google.com:80 a.b.c.d

此时,在浏览器里键入:http://a.b.c.d:1234,就会看到Google的页面了。

在绑定1234端口的时候,可以省略前面的ip,如此一来,1234端口就仅仅绑定在localhost地址上,更安全:

ssh -NfL 1234:www.google.com:80 a.b.c.d

此时浏览的话就要在a.b.c.d机器上使用http://localhost:1234了。

何时使用本地Tunnel?

比如说你在本地访问不了某个网络服务(如www.google.com),而有一台机器(如:a.b.c.d)可以,那么你就可以通过这台机器来访问。

2:远程Remote(ssh -NfR)

ssh -NfR 1234:localhost:22 a.b.c.d

接着转到a.b.c.d机器,使用如下命令:

ssh -p 1234 localhost

需要注意的是上下两个命令里的localhost不是同一台。这时你会发现自己已经连上最开始命令里的localhost机器了,也就是执行“ssh -NfR”的那台机器。

何时使用远程Tunnel?

比如当你下班回家后就访问不了公司内网的机器了,遇到这种情况可以事先在公司内网的机器上执行远程Tunnel,连上一台公司外网的机器,等你下班回家后就可以通过公司外网的机器去访问公司内网的机器了。

3:动态Dynamic(ssh -NfD)

ssh -NfD 1234 a.b.c.d

如此一来就建立了一台Socket代理机器,接着在浏览器上设置Socket代理:地址是localhost,端口是1234,从此以后,你的访问都是加密的了!你可以通过访问WhatIsMyIP来确认自己现在的IP,看看是不是已经变成a.b.c.d了。

测试阶段,也可以把端口绑定在外网地址上,如此一来,你在浏览器上就可以使用外网地址设置Socket代理,但这仅限于测试,否则,你的机器就不安全了, 随时可能成为肉鸡。对于Windows用户来说,如果讨厌命令行,还可以使用MyEnTunnel来实现同样的功能,配合Firefox的 FoxyPorxy,基本就无敌了,至于具体的配置方法,小崔已经写好了:使用Firefox+foxyProxy+SSH翻山越岭。如果你使用的是Chrome的话,则可以选择Proxy Switchy!来实现同样的效果,恕不多言。

补充:和MyEntunnel比起来,似乎Bitvise Tunnelier更爽一点,下载的话别搞错了,要的是客户端,个人用户免费。

何时使用动态Tunnel?

中国人都知道。

友情提示:

在实验过程中如果想确认端口是否已经生效,可以使用lsof命令,例如:/usr/sbin/lsof -i:1234
from http://hi.baidu.com/thinkinginlamp/blog/item/4e1d510fe7c811216059f3ea.html

参考文档:

上班族ssh tunnel求生手冊
反向建立 SSH Tunnel、免 VPN 連回公司
---------------------------------------------------------------------------------------

用SSH来传输文件

PuTTY 提供了两个文件传输工具
  • PSCP (PuTTY Secure Copy client)
  • PSFTP (PuTTY SFTP client)
PSCP 通过 SSH 连接,在两台机器之间安全的传输文件,可以用于任何 SSH(包括 SSH v1、SSH v2) 服务器
PSFTP 则是 SSH-2 中新增的特性,使用的是新的 SFTP 协议,使用上与传统的 FTP 类似。事实上 PSCP 如果发现 SFTP 可用,PSCP就会使用 SFTP 协议来传输文件,否则还是 SCP 协议。PSFTP 与 PSCP 相比,PSFTP 的优点是可以与服务器进行交互,遍历服务器上的文件系统,在一个会话中上传或下载多个文件。而 PSCP 只能一次传输一个文件,传输完毕后立刻终止会话。

PSCP 的使用

在控制台直接执行 pscp 可以看到帮助
C:\>pscp
PuTTY Secure Copy client
Release 0.58
Usage: pscp [options] [user@]host:source target
pscp [options] source [source...] [user@]host:target
pscp [options] -ls [user@]host:filespec
Options:
-V print version information and exit
-pgpfp print PGP key fingerprints and exit
-p preserve file attributes
-q quiet, don't show statistics
-r copy directories recursively
-v show verbose messages
-load sessname Load settings from saved session
-P port connect to specified port
-l user connect with specified username
-pw passw login with specified password
-1 -2 force use of particular SSH protocol version
-4 -6 force use of IPv4 or IPv6
-C enable compression
-i key private key file for authentication
-batch disable all interactive prompts
-unsafe allow server-side wildcards (DANGEROUS)
-sftp force use of SFTP protocol
-scp force use of SCP protocol

C:\>
可以看出 PSCP 的使用是很简单的,把常用的几个选项说一下:
  • -q 安静模式,传输文件时什么也不显示,否则会显示出文件的传输进度,默认是关闭的
  • -P port 指定服务器的 SSH 端口,注意这个是大写字母 P,默认是 -P 22,如果主机的 SSH 端口就是 22,就不用指定了
  • -l user 指定以哪个用户的身份登录主机,如果没有指定,则 PSCP 会在 PuTTY 保存的同名 Session 中获得默认的用户名称。用户名称也可以和主机名称写在一起,用 @ 分割开,比如:username@server
  • -pw passwd 指定登录时所用的口令为 passwd
  • -i keyfile 就是指定登录时所用的密钥文件
  • 最后面指定的主机名也可以是 PuTTY 中保存的 Session 名称。比如我们在 PuTTY 中保存了一个名为 foobarserver 的会话,而我们所在的网络又的确没有名为 foobarserver 的主机名称。而在这个 foobarserver 会话中保存的主机名称是 demo-server,保存的自动登录的用户是 taylor。那么用命令
    pscp c:\autoexec.bat foobarserver:backup/
    就把本地的 c:\autoexec.bat 复制到了主机 demo-server 上的用户 taylor 所在的主目录下的 backup 子目录中(这个路径可能是 /home/taylor/backup

所以 PSCP 大致用法的例子就是:
pscp -P 22 -i c:\path\your-private-key.ppk -C username@server:/remote/path/
下面还是用一些实例来说明会比较简单一些:
把本地的 C:\path\foo.txt 复制到远程主机 192.168.6.200 的 /tmp 目录下
pscp c:\path\foo.txt 192.168.6.200:/tmp
把本地的 C:\path\foo.txt 复制到主机 192.168.6.200 的 /tmp 目录下,但是以主机上的用户 taylor 的权限执行
pscp c:\path\foo.txttaylor@192.168.6.200:/tmp
或者是
pscp-l taylorc:\path\foo.txt 192.168.6.200:/tmp
把本地的 C:\path\foo.txt 传送到主机 192.168.6.200 的 /tmp 目录下,但是主机的 SSH 端口是 3122
pscp-P 3122c:\path\foo.txt 192.168.6.200:/tmp
把本地的 C:\path\foo.txt 复制到主机 192.168.6.200 的用户 taylor 的主目录下
pscp c:\path\foo.txt taylor@192.168.6.200:.
把主机 192.168.6.200 上的用户 taylor 主目录下的所有 *.tgz 文件拷贝到本地的 c:\backup 目录中,如果 SSH 版本是 SSH v1,那这个命令就会出错。
pscp taylor@192.168.6.200:*.tgz c:\backup

再来看看 PSFTP

在控制台执行命令 psftp -h,可以得到 psftp 的帮助
C:\>psftp -h
PuTTY Secure File Transfer (SFTP) client
Release 0.58
Usage: psftp [options] [user@]host
Options:
-V print version information and exit
-pgpfp print PGP key fingerprints and exit
-b file use specified batchfile
-bc output batchfile commands
-be don't stop batchfile processing if errors
-v show verbose messages
-load sessname Load settings from saved session
-l user connect with specified username
-P port connect to specified port
-pw passw login with specified password
-1 -2 force use of particular SSH protocol version
-4 -6 force use of IPv4 or IPv6
-C enable compression
-i key private key file for authentication
-batch disable all interactive prompts

C:\>
用法与 PSCP 大同小异,虽然有个 -load 选项,其实这个没啥用,后面用主机名的时候,与 PSCP 一样直接用上会话名称就可以了。
用 PSFTP 登录到服务器上以后,操作与 FTP 差不多,这里简单的说一下吧:
  • open 登录主机
    open [username@]<sessname|hostname|ip> [port]
    比如:
    • open taylor@demo-server 3022
      就是以用户 taylor 的身份,登陆到主机 demo-server 上,SSH 端口是 3022
    • open demo-server
      登陆 demo-server,这里的 demo-server 可以是PuTTY 中已经保存的会话名称,也可以是主机的名称,如果主机名称与会话名称相同,以会话名称为准。
  • close 关闭 SFTP 连接
    这个没啥说的,close 就关闭了 SFTP 连接
  • quit 结束本次的 SFTP 会话
    也没啥用法,就是关闭了 PSFTP 这个程序
  • help [command] 帮助
    直接打 help 就可以看到帮助指令,后面指定上 一个命令就可以查看该命令的帮助,比如: help open
  • cd [directory] 改变当前目录
  • pwd 察看当前目录
  • lcd [directory] 改变本地目录
  • lpwd 察看本地当前目录
  • get [-r] <filename|directory> 从服务器下载一个文件/目录,这个命令不能用通配符,参数 -r 可以递归下载整个目录
  • put [-r] <filename|directory> [dest] 把文件/目录上传到服务器,这个命令不能用通配符,参数 -r 可以递归上传整个目录
  • mget [-r] <filename|directory> 从服务器下载一批文件/目录,可以用通配符,-r 的含义与 get 一样
  • mget [-r] <filename|directory> [dest] 把一批文件/目录上传到服务器,可以用通配符,-r 的含义与 put 一样
  • reget [-r] <filename|directory> 从服务器续传下载一个文件/目录,这个命令不能用通配符,-r 的含义与 get 一样
  • reput [-r] <filename|directory> [dest] 把一批文件/目录续传上传到服务器,这个命令不能用通配符,-r 的含义与 put 一样
  • dir [directory] 列目录
  • ls 和 dir 一样
  • chmod [file|directory] 改变文件的权限,与 Unix 的 chmod 命令类似
  • del <filename> 删除文件,要注意的是 del 只能删除文件
  • rm 与 del 一样
  • mkdir <new-directory-name> 创建一个目录
  • rmdir <directory> 删除一个空目录,只有空目录才可以被删除
  • mv <source-file|source-directory> <dest-file|dest-directory> 改名/移动。如果源和目的都是文件或目录,则是改名。如果目的是目录的话,则是移动。
  • ! 在本地命令前加一个感叹号,就可以直接执行

其他可选的 SFTP 客户端

FileZilla : [url]http://filezilla.sf.net[/url]
WinSCP : [url]http://www.winscp.net[/url]

用 Plink 更方便快捷的执行远程主机上的命令

Plink 是 PuTTY 的命令行连接工具,主要用于自动化工作的处理。
直接在控制台执行 plink,可以看到 Plink 的帮助
C:\>plink
PuTTY Link: command-line connection utility
Release 0.58
Usage: plink [options] [user@]host [command]
("host" can also be a PuTTY saved session name)
Options:
-V print version information and exit
-pgpfp print PGP key fingerprints and exit
-v show verbose messages
-load sessname Load settings from saved session
-ssh -telnet -rlogin -raw
force use of a particular protocol
-P port connect to specified port
-l user connect with specified username
-batch disable all interactive prompts
The following options only apply to SSH connections:
-pw passw login with specified password
-D [listen-IP:]listen-port
Dynamic SOCKS-based port forwarding
-L [listen-IP:]listen-port:host:port
Forward local port to remote address
-R [listen-IP:]listen-port:host:port
Forward remote port to local address
-X -x enable / disable X11 forwarding
-A -a enable / disable agent forwarding
-t -T enable / disable pty allocation
-1 -2 force use of particular protocol version
-4 -6 force use of IPv4 or IPv6
-C enable compression
-i key private key file for authentication
-m file read remote command(s) from file
-s remote command is an SSH subsystem (SSH-2 only)
-N don't start a shell/command (SSH-2 only)

C:\>
看上去 Plink 的使用方法、参数与PSCP、PSFTP都很类似。
  • -P port 指定服务器的 SSH 端口,注意这个是大写字母 P,默认是 -P 22,如果主机的 SSH 端口就是 22,就不用指定了
  • -l user 指定以哪个用户的身份登录主机,如果没有指定,则 PSCP 会在 PuTTY 保存的同名 Session 中获得默认的用户名称。用户名称也可以和主机名称写在一起,用 @ 分割开,比如:username@server
  • -pw passwd 指定登录时所用的口令为 passwd
  • -i keyfile 就是指定登录时所用的密钥文件
  • -m file 如果执行的命令很多的话,可以把命令写到文件中,然后用这个参数来指定
还是用一些实际的例子来说明一下 Plink 吧
还记得前面说到 PuTTY 的自动执行命令那个配置么?在说到那个配置的时候,我们演示了一个简单的 Tomcat 重新启动的命令,这个命令是要写在 PuTTY 的 Remote command 里面去。现在我们用 Plink 来实现同样的功能:
假设连接的主机是 192.168.6.200,SSH 的端口是 3022,用户是 taylor:
plink -P 3022 taylor@192.168.6.200 export CATALINA_HOME="~/apache-tomcat-5.5.17";export JAVA_HOME="~/jdk1.5.0_07";export PATH=$JAVA_HOME/bin;$PATH ; cd $CATALINA_HOME/bin;./shutdown.sh;./startup.sh;tail -f $CATALINA_HOME/logs/catalina.out
如果在 PuTTY 中保存了一个名为 192.168.6.200 的会话,注意,这个会话的名称与主机 IP 一样,在会话中已经正确保存了端口 3022,指定了默认的用户是 taylor,现在这个命令就可以简化为:
plink 192.168.6.200 export CATALINA_HOME="~/apache-tomcat-5.5.17";export JAVA_HOME="~/jdk1.5.0_07";export PATH=$JAVA_HOME/bin;$PATH ; cd $CATALINA_HOME/bin;./shutdown.sh;./startup.sh;tail -f $CATALINA_HOME/logs/catalina.out
用 date 命令查看一下主机上的时间,并且格式化输出:
plink 192.168.6.200 date "+%F %T"
大家实际执行一下命令看看,会发现,这个命令并没有返回我们期望的结果,而是返回了一个错误:
C:\>plink 192.168.6.200 date "+%F %T"
date: too many non-option arguments: %T
Try `date --help' for more information.
可是在服务器上直接执行命令 date "+%F %T",的确是正确无误的,哪里出了问题呢?这是因为Windows的控制台会把两个双引号之间的字符串作为一个参数传递给被执行的程序,而不会把双引号也传递给程序。我们做这样一个小小的实验来说明一下这个问题:
比 如在 c:\tmp 文件夹里建立三个文件夹,名称分别为:"foo"、"bar"、"foo bar"。然后在 foo 这个文件夹里面建立一个名为“foo.log”的空文件,在“bar”这个文件夹里建立一个名为“bar.log”的空文件,在“foo bar”这个文件夹里建立一个名为“foo-bar.log”的空文件。
然后在控制台下进入 c:\tmp 这个文件夹,执行如下命令:
dir foo bar
结果是列出“foo bar”这个文件夹里的内容,还是分别列出“foo”和“bar”文件夹里的东西呢?正确答案是后者。
要想正确列出“foo bar”文件夹里的东西,就需要用双引号把"foo bar"引起来
C:\tmp>dir foo bar
Volume in drive C is System
Volume Serial Number is 9C51-A51C

Directory of C:\tmp\foo

2006-11-22 09:48 <DIR> .
2006-11-22 09:48 <DIR> ..
2006-11-16 11:58 0 foo.log
1 File(s) 0 bytes

Directory of C:\tmp\bar

2006-11-22 09:48 <DIR> .
2006-11-22 09:48 <DIR> ..
2006-11-16 11:58 0 bar.log
1 File(s) 0 bytes
2 Dir(s) 1,107,345,408 bytes free

C:\tmp>dir "foo bar"
Volume in drive C is System
Volume Serial Number is 9C51-A51C

Directory of C:\tmp\foo bar

2006-11-22 09:48 <DIR> .
2006-11-22 09:48 <DIR> ..
2006-11-16 11:58 0 foo-bar.log
1 File(s) 0 bytes
2 Dir(s) 1,107,345,408 bytes free

C:\tmp>
说 到这里,就会明白上面的那个命令 plink 192.168.6.200 date "+%F %T" 其实在主机上执行的真实命令是 date +%F %T,而不是命令行中指定的 date "+%F %T"。不过还好,Windows 的控制台可不认得单引号,所以上面那个命令的正确用法应该是:
c:\>plink 192.168.6.200 date '+%F %T'
2006-11-22 09:39:57
我经常需要登录到服务器上把 ADSL 重新拨号,可以把下面的命令写到一个文本文件中,比如保存到了 C:\adsl-restart.command.txt
echo "stoping..."
/sbin/adsl-stop
echo "starting..."
/sbin/adsl-start
echo "done."
/sbin/adsl-status
然后执行如下命令:
plink -m c:\adsl-restart.command.txt root@192.168.6.251
我经常要查看 Tomcat 的运行日志
plink taylor@192.168.6.200 tail -f ~/apache-tomcat-5.5.17/logs/catalina.out
每天都要看服务器上的剩余空间,就用这个命令:
plink taylor@192.168.6.200 df -k
假 设 [url]www.chaifeng.com[/url] 连接着另外一个网段 10.204.26.0,有台内网IP 为 10.204.26.21 的 Solaris 8主机只能用 telnet 登录,为了防止被监听,我们可以用 Plink 建立一个隧道,隧道开放 120 秒钟,如果隧道没有被使用,就自动断开连接,然后我们在本地就可以用命令 telnet localhost 2623 的安全登录那台 Solaris 8 主机了。
plink -L 2623:10.204.26.21:23 [url]www.chaifeng.com[/url] sleep 120
在主机 [url]www.chaifeng.com[/url] 上正在运行着 tor,默认的监听地址是 127.0.0.1:9050,用 Plink 建立一个隧道,然后浏览器上配置代理服务器为 127.0.0.1,端口是 9050,这样就能够安全的使用 tor 代理了,不用担心从我们的机器到主机 [url]www.chaifeng.com[/url] 有被监听的可能了。
plink -C -N -L 9050:127.0.0.1:9050 taylor@[url]www.chaifeng.com[/url]
结合上 PSCP 我们还可以完成文件的每天备份
plink taylor@192.168.6.200 tar jcf $(date '+documents.%F.tar.bz2') ~/documents
pscp taylor@192.168.6.200:$(date '+do
---------------------------------------------------------------------------------
在考虑怎样在Android手机上使用SSH tunnel翻墙
目前在PC上使用SSH tunnel翻墙是一个相当广泛使用的方案,国外SSH帐号的获取不是太难,购买起来价格也比VPN帐号要便宜。但是在智能手机上目前还不能使用SSH方 案,只能用VPN。Android系统是基于Linux的,特别是root了之后,基本上要玩什么都随心所欲了。因此Android上是应该也可以使用 SSH tunnel的。
先看看Windows上是怎样设置SSH翻墙的:
  • 首先需要有个支持dynamic port forwarding的SSH client,这个SSH client能开放出SOCKS服务
  • 如果浏览器(或者其他程序)支持使用SOCKS proxy,设置使用SSH client开放出来的SOCKS端口,就可以使用了
  • 如果浏览器(或者其他程序)不支持SOCKS proxy,只支持HTTP proxy,就需要再运行一个支持SOCKS的代理程序(例如Privoxy),将HTTP转成SOCKS

在Android上就要麻烦一点了,因为需要网络通讯的不仅仅是浏览器,很多Android application都需要访问网络,但是它们并不支持proxy——连HTTP proxy都不支持,更不用说SOCKS了。它们只会直接连接目标站点,如图中虚线所示,然后撞墙。
但是Linux有iptables,可以设置iptables规则(需要root权限),将HTTP/HTTPS请求forward到一个 transparent SOCKS proxy去。transparent SOCKS proxy的作用是将任意TCP连接转成SOCKS连接,这样就可以走SSH tunnel出去了。我分析过几乎所有的Android应用访问网络都是走HTTP/HTTPS协议的,所有仅仅处理HTTP/HTTPS就够了。

Android上支持dynamic port forwarding的SSH client有ConnectBot,不过ConnectBot是一个有界面的应用,似乎不能由其他程序来控制,这样就不好做到翻墙软件的傻瓜化了。应该还是弄一个命令行的ssh client更合适。
在网上搜索了一下,开源的transparent SOCKS proxy有几个:transocks_evTranSocksredsocks。从文档上看,似乎transocks_ev比较适合。
但是,我现在面临的困难在于我不熟悉如何交叉编译Android平台程序(C语言),了解了一下如何搭建Android交叉编译环境,似乎挺麻烦 (对我而 言)。而且要让普通Linux上可运行的sshd和transocks port到Android上,也许还有一些代码要修改。不知道有没有Android系统高手能够帮忙?
from http://good-good-study.appspot.com/blog/posts/20001
在上一篇博客中,提出了在Android手机上使用SSH tunnel的想法。几天下来有了一些进展。
首先,非常感谢Sunner,他帮忙编译出Android平台的transocks_ev binary,并且解决了一些在Android平台上运行的问题。
在实验中,用ConnectBot + transocks_ev + iptables,HTTP和HTTPS请求都能重定向到SSH tunnel了,测试了浏览器和其他一些应用,无需任何额外设置就可正常访问网络。不过目前没有考虑使用非HTTP/HTTPS的应用。但现在还有两个问 题:
  1. DNS查询还是直接出去,不能避免DNS污染
  2. 现在用ConnectBot作为ssh client,并不合适:
    • 在port forwarding时ConnectBot CPU占用非常高,达到99%,估计是有bug。
    • ConnectBot的连接和断开需要手动控制,密码也要在界面输入,无法做到整个翻墙过程单击执行。


对于第一个问题,transocks_ev 不支持UDP,因此无法tunnel DNS查询请求。我在考虑参考CMWrap的方案,做一个DNS proxy,转成TCP请求发出去。
对于第二个问题,想用一个命令行ssh来代替ConnectBot。目前在Android上常用的是dropbear,但dropbear不支持SOCKS。查了linux上支持SOCKS的ssh client有OpenSSH和lsh(还有没有其他?),但是Sunner尝试了编译OpenSSH和lsh都不成功,因为它俩都太依赖gnu的一些东西了,比如glibc、glib等,而android上所有的对应的库都是从简的。因此暂时还是先用着ConnectBot,并将CPU高的问题反馈给开发者,看看有没有什么回应. from http://good-good-study.appspot.com/blog/posts/25001
------------------------------------------------------------------------------

SSH隧道技术简介

如果你遇到了以下问题,那么你应该阅读这篇文章
  1. 我听说过这种技术,我对它很感兴趣
  2. 我想在家里访问我在公司的机器(写程序,查数据,下电影)。
  3. 公司为了防止我们用XX软件封锁了它的端口或者服务器地址。
  4. 公司不让我们上XX网站,限制了网址甚至IP。
  5. 公司不让我们看关于XX的信息,甚至花血本买了XX设备,能够对内容进行过滤。一看XX内容,链接就中断了。
  6. 我爸是搞电脑的,他在家里的路由器上动了手脚,我不能看XXX了。
带着这些问题,我们先从什么是ssh隧道开始。

什么是SSH隧道

首 先看下面这张图,我们所面临的大部分情况都和它类似。我们的电脑在右上角,通过公司带有防火墙功能的路由器接入互联网(当然可能还有交换机什么的在中间连 接着你和路由器,但是在我们的问题中交换机并不起到什么关键性的作用)。右下脚的部分是一个网站的服务器,它是我们公司防火墙策略的一部分,也就是说公司 不希望我们访问这个服务器。在右上角还有一台机器,它也是属于我们的。但是这台机器并不在我们公司里面,换句话说他不受到公司防火墙的限制。最后也是最重 要的一点是,我们能够在公司通过互联网直接访问这台机器。或者说这台位于公司防火墙外面的机器需要拥有一个独立的互联网IP,同时公司的防火墙规则不会屏 蔽这台机器,并且这台机器运行着一个OpenSSH服务器。

现 在,我们清楚地知道了自己所处的网络环境。并且不难理解我们在公司无法访问那个服务器的原因是:线路A-B-C上A-B之间的防火墙屏蔽了对那个服务器的 访问。与此同时,我们也很快注意到,线路A-B-D之间、D-C之间是不受阻碍的。相信你已经想到了,在A-B之间的防火墙不会屏蔽对机器d的访问。因此 我们可以通过机器d建立一个通道A-B-D-C,从而访问到机器c上的数据。
这条通道可以用很多技术来建立,这里我们仅仅介绍如何使用SSH服务器来建立这样一个通道-他被称为SSH隧道。

如何建立本地SSH隧道

在我们计划建立一个本地SSH隧道之前,我们必须清楚下面这些数据:
  1. 中间服务器d的IP地址
  2. 要访问服务器c的IP地址
  3. 要访问服务器c的端口
现在,我们把上面这张图变得具体一些,给这些机器加上IP地址。并且根据下面这张图列出我们的计划:

  1. 需要访问234.234.234.234的FTP服务,也就是端口21
  2. 中间服务器是123.123.123.123
现在我们使用下面这条命令来达成我们的目的
1.ssh -N -f -L 2121:234.234.234.234:21 123.123.123.123
2.ftp localhost:2121 # 现在访问本地2121端口,就能连接234.234.234.234的21端口了
这里我们用到了SSH客户端的三个参数,下面我们一一做出解释:
  • -N 告诉SSH客户端,这个连接不需要执行任何命令。仅仅做端口转发
  • -f 告诉SSH客户端在后台运行
  • -L 做本地映射端口,被冒号分割的三个部分含义分别是
    • 需要使用的本地端口号
    • 需要访问的目标机器IP地址(IP: 234.234.234.234)
    • 需要访问的目标机器端口(端口: 21)
  • 最后一个参数是我们用来建立隧道的中间机器的IP地址(IP: 123.123.123.123)
我们再重复一下-L参数的行为。-L X:Y:Z的含义是,将IP为Y的机器的Z端口通过中间服务器映射到本地机器的X端口。
在这条命令成功执行之后,我们已经具有绕过公司防火墙的能力,并且成功访问到了我们喜欢的一个FTP服务器了。

如何建立远程SSH隧道

通 过建立本地SSH隧道,我们成功地绕过防火墙开始下载FTP上的资源了。那么当我们在家里的时候想要察看下载进度怎么办呢?大多数公司的网络是通过路由器 接入互联网的,公司内部的机器不会直接与互联网连接,也就是不能通过互联网直接访问。通过线路D-B-A访问公司里的机器a便是不可能的。也许你已经注意 到了,虽然D-B-A这个方向的连接不通,但是A-B-D这个方向的连接是没有问题的。那么,我们能否利用一条已经连接好的A-B-D方向的连接来完成 D-B-A方向的访问呢?答案是肯定的,这就是远程SSH隧道的用途。
与本地SSH一样,我们在建立远程SSH隧道之前要清楚下面几个参数:
  • 需要访问内部机器的远程机器的IP地址(这里是123.123.123.123)
  • 需要让远程机器能访问的内部机器的IP地址(这里因为是想把本机映射出去,因此IP是127.0.0.1)
  • 需要让远程机器能访问的内部机器的端口号(端口:22)
在清楚了上面的参数后,我们使用下面的命令来建立一个远程SSH隧道
1.ssh -N -f -R 2222:127.0.0.1:22 123.123.123.123
现在,在IP是123.123.123.123的机器上我们用下面的命令就可以登陆公司的IP是192.168.0.100的机器了。
1.ssh -p 2222 localhost
-N,-f 这两个参数我们已经在本地SSH隧道中介绍过了。我们现在重点说说参数-R。该参数的三个部分的含义分别是:
  • 远程机器使用的端口(2222)
  • 需要映射的内部机器的IP地址(127.0.0.1)
  • 需要映射的内部机器的端口(22)
例如:-R X:Y:Z 就是把我们内部的Y机器的Z端口映射到远程机器的X端口上。

建立SSH隧道的几个技巧

自动重连
隧道可能因为某些原因断开,例如:机器重启,长时间没有数据通信而被路由器切断等等。因此我们可以用程序控制隧道的重新连接,例如一个简单的循环或者使用 djb’s daemontools . 不管用哪种方法,重连时都应避免因输入密码而卡死程序。关于如何安全的避免输入密码的方法,请参考我的 如何实现安全的免密码ssh登录 。这里请注意,如果通过其他程序控制隧道连接,应当避免将SSH客户端放到后台执行,也就是去掉-f参数。
保持长时间连接
有些路由器会把长时间没有通信的连接断开。SSH客户端的TCPKeepAlive选项可以避免这个问题的发生,默认情况下它是被开启的。如果它被关闭了,可以在ssh的命令上加上-o TCPKeepAlive=yes来开启。
另一种方法是,去掉-N参数,加入一个定期能产生输出的命令。例如: top或者vmstat。下面给出一个这种方法的例子:
1.ssh -R 2222:localhost:22 123.123.123.123 "vmstat 30"
检查隧道状态
有 些时候隧道会因为一些原因通信不畅而卡死,例如:由于传输数据量太大,被路由器带入stalled状态。这种时候,往往SSH客户端并不退出,而是卡死在 那里。一种应对方法是,使用SSH客户端的ServerAliveInterval和ServerAliveCountMax选项。 ServerAliveInterval会在隧道无通信后的一段设置好的时间后发送一个请求给服务器要求服务器响应。如果服务器在 ServerAliveCountMax次请求后都没能响应,那么SSH客户端就自动断开连接并退出,将控制权交给你的监控程序。这两个选项的设置方法分 别是在ssh时加入-o ServerAliveInterval=n和-o ServerAliveCountMax=m。其中n, m可以自行定义。
如何将端口绑定到外部地址上
使 用上面的方法,映射的端口只能绑定在127.0.0.1这个接口上。也就是说,只能被本机自己访问到。如何才能让其他机器访问这个端口呢?我们可以把这个 映射的端口绑定在0.0.0.0的接口上,方法是加上参数-b 0.0.0.0。同时还需要打开SSH服务器端的一个选项-GatewayPorts。默认情况下它应当是被打开的。如果被关闭的话,可以在/etc /sshd_config中修改GatewayPorts no为GatewayPorts yes来打开它。
如何寻找中间服务器
如果你家里使用ADSL上网,多半你会比较幸运。一般的ADSL(例如 联通 的ADSL)都是有互联网地址的。你只需要在家里的路由器上一台装有OpenSSH server机器的SSH端口映射出去即可。同时一些提供SSH访问的虚拟主机也可以用于这一用途。例如: Hostmonser 或者 Dreamhost .

通过SSH隧道建立SOCKS服务器

如果我们需要借助一台中间服务器访问很多资源,一个个映射显然不是高明的办法(事实上,高明确实没有用这个方法)。幸好,SSH客户端为我们提供了通过SSH隧道建立SOCKS服务器的功能。
通过下面的命令我们可以建立一个通过123.123.123.123的SOCKS服务器。
1.ssh -N -f -D 1080 123.123.123 # 将端口绑定在127.0.0.1上
2.ssh -N -f -D 0.0.0.0:1080 123.123.123.123 # 将端口绑定在0.0.0.0上
通过SSH建立的SOCKS服务器使用的是SOCKS5协议,在为应用程序设置SOCKS代理的时候要特别注意。

总结

至 此,我们已经对如何利用SSH隧道有一个基本的认识了。现在,文章开始时的那些问题应该迎刃而解了吧。这里要特别说一下,由于SSH隧道也使用了SSH加 密协议,因此是不会被防火墙上的内容过滤器监控到的。也就是说一切在隧道中传输的数据都是被加密的。当然,离开隧道后的数据还是会保持自己原有的样子,没 有加密的数据还是会被后续的路由设备监控到。

参考文献

OpenSSH网站
---------------------------------------------------------------------------------------------

SSH配置

SSH是什么?SSH(Secure Shell)是一种建立在应用层和传输层基础上、专为远程登录会话和其他网络服务提供安全性的协议。 利用SSH协议可以有效防止远程管理过程中的信息泄露问题。 透过ssh可以对所有传输的数据进行加密,也能够防止DNS欺骗和IP欺骗。 SSH之另一项优点为其传输的数据是经过压缩的,所以可以加快传输的速度。SSH有很多功能,它既可以代替Telnet,又可以为FTP、POP、甚至为 PPP提供一个安全的“通道”。 如果你有一个国外的ssh账号的话,则可以使用SSH隧道作为一个安全上网代理。

1.SSH在Windows 客户端配置

Windows下常用的SSH客户端有开源的Putty以及在其基础上的加上GUI外壳 的MyEntunnel。使用MyEntunnel可以避免记忆复杂的命令行,还可以安全的保存密码。但是有个问题,通过MyEnTunnel或者 plink下载或者看视频速度很慢,最高不超过35KB/s。(由于Release版的Putty限速于40KB/s,Dev版的Putty无此问题,详 情见:http://omobox.com/memo/tunnelier-instead-of-myentunnel.html)
推荐另一款SSH客户端Tunnelier,相比MyEntunnel有两点优势:1.不限速2.更方便的使用公钥/私钥系统做SSH认证。
前者的重要性毋庸置疑,而后者使用生成的公钥而非密码认证在安全上有更多的优势,详情在此文有 更多的探讨。 软件设置比较简单: Login选项卡,输入ssh服务器的登录信息。 Options选项卡,On Login部分把几个勾都去掉,很多时候你的SSH提供商并没有给你Shell Access权限。 Services选项卡,SOCKS/HTTP Proxy Forwarding部分 Enabled,修改本地监听端口,形成Socket v5 代理。 公钥配置使用Keypair Manager,如下图,Generate一对密钥,Export出公钥Public Key, Import进服务器。登陆时用自己的私钥,每次输入口令Passphrase,即可。
然后Save Profile As另存配置。
Tips:
可以从命令行运行
Tunnelier:tunnelier -profile=profilename.tlp -loginOnStartup

2.SSH在Linux客户端配置

Linuxer不用GUI,因而这里以Ubuntu 10.04 Lucid为例。
ssh -fnN -D localport -p hostport 'username@hostname'
其中 hostname是SSH主机名或者IP地址 hostport是远程主机的SSH服务端口,当其非默认端口22时需要在这里设置。 localport即Socket v5 Proxy监听端口,一般SSH设定为7070. 剩下参数意义如下
-q :- be very quite, we are acting only as a tunnel.
-f :- move the ssh process to background, as we don’t want to interact with this ssh session directly.
-N :- Do not execute remote command.
-n :- redirect standard input to /dev/null.
其中-N很重要,有的时候,主机商没有给你SSH Shell Access权限时,必须要开启,否则有可能自动关闭这个SSH连接。
  • 自动重连
Linux系统中不像Windows有非常好用的GUI,但是却又异常强大的bash,利用它,我们可以完成SSH自动重连。 要使用重连的机制,需要先建立远程服务器公钥对本机的私钥配对形成信任关系,使用ssh-copy-id这个小工具,这样才可以免输密码。

(1)先生成一对密钥。
ssh-keygen -t rsa
这个命令生成一个密钥对:id_rsa(私钥文件)和id_rsa.pub(公钥文件)。默认被保存在~/.ssh/目录下。
(2)建立信任关系
通过CPanel将公钥import进SSH服务器或者scp到服务器,或者最最简单方便的ssh-copy-id这个脚本。
$ ssh-copy-id -i ~/.ssh/id_rsa.pub  username@hostname

If you need shell access please contact support.
Now try logging into the machine, with "ssh -p XXXX 'user@host'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.
如果你和我一样,使用的SSH服务非默认的22端口,你需要使用这个修改版的ssh-copy-id(引自此文)。
#!/bin/sh

# Shell script to install your identity.pub on a remote machine
# Takes the remote machine name as an argument.
# Obviously, the remote machine must accept password authentication,
# or one of the other keys in your ssh-agent, for this to work.

ID_FILE="${HOME}/.ssh/identity.pub"

while getopts ':i:p:P:h' OPTION
do
    case $OPTION in
        i)
        if [ -n "$OPTARG" ]; then
            if expr "$OPTARG" : ".*.pub" > /dev/null ; then
                ID_FILE="$OPTARG"
            else
                ID_FILE="$OPTARG.pub"
            fi
        fi
        ;;
        P|p)
            PORT=$OPTARG;
        ;;
        h)
            echo "Usage: $0 [-i [identity_file]] [user@]machine" >&2
            exit 1
        ;;
    esac;
done;

shift $(($OPTIND - 1))

if [ $# -lt 1 ] && [ x$SSH_AUTH_SOCK != x ] ; then
   GET_ID="$GET_ID ssh-add -L"
fi

if [ -z "`eval $GET_ID`" ] && [ -r "${ID_FILE}" ] ; then
  GET_ID="cat ${ID_FILE}"
fi

if [ -z "`eval $GET_ID`" ]; then
  echo "$0: ERROR: No identities found" >&2
  exit 1
fi

if [ -z $PORT ]; then
    PORTOPTION=""
else
    PORTOPTION="-p $PORT "
fi;

{ eval "$GET_ID" ; } | ssh $PORTOPTION $1 "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys" || exit 1

cat <
如此调用即可~
ssh-copy-id -p local -i ~/.ssh/id_rsa.pub username@hostname
3.自动重连脚本(来自Blogkid大大)
curl -s -I http://www.google.com/ –socks5 localhost:7070 > /dev/null
[ $? -gt 0 ] && ssh -fN username@hostname -D 7070
脚本很简单,就是使用curl通代理访问一下google(这里也可以是任意别的网站)。如果访问失败了,就重开一个ssh进程监听7070端口。
--------------------------------------------------------------------------------------------------
一段脚本让断掉的SSH Tunnel自动重连

写了一段脚本来检测ssh tunnel是否还存活。如果没有就启动一个新的连接。
脚本内容:
curl -s -I http://www.google.com/ –socks5 localhost:7070 > /dev/null
[ $? -gt 0 ] && ssh -fN username@hostname -D 7070
脚本很简单,就是使用curl通代理访问一下google(这里也可以是任意别的网站)。如果访问失败了,就重开一个ssh进程监听7070端口。
要使用重连的机制,需要先建立远程服务器对本机的信任关系,这样才可以免输密码。如果觉得搭建信任关系过程太繁琐,可以使用ssh-copy-id这个小工具。
上述两行脚本可以加入到~/.profile(有的也叫.bash_profile)中,这样每次打开屏幕都会做检查,每次开机登录后也会自动连接。如果愿意,也可以加在Crontab中,每隔几分钟跑一下。
这样设置之后,平时基本上不用关心代理了,它会安静地在后台一直跑着。
------------------------------------------------------------------------------

SSH使用私钥自动登录

生成私钥/公钥对

ssh-keygen -t rsa

上传公钥到服务器

ssh-copy-id -i ~/.ssh/id_rsa.pub root@1.2.3.4

创建快捷方式

edit .bashrc

alias your_ssh='root@1.2.3.4'
------------------------------------------------------------------------------

为什么要用公钥/私钥而不是密码去做SSH身份验证?

SSH提供了很多种不同的身份验证,其中最常用的两种便是密码验证和基于公钥/私钥的身份验证。
基于公钥/私钥的身份验证有非常多的优点。
首先,公钥/私钥可以从根本上挫败监听来截取验证信息的企图。
公钥/私钥验证本质上是一种 零知识证明。即,在身份验证的过程中,服务器并不需要知道用户的私钥是什么。【注:公钥/私钥验证并不是零知识证明,感谢 snnn 指正。】
公钥/私钥验证在身份验证的过程中,服务器只需要知道用户的公钥,而用户则使用自己的私钥对一组数据签名,并在服务器端进行验证。服务器并不需要知道用户的私钥。目前为止,还没有有效的方法能从这些信息推导出私钥。
与密码相比,这种方法有显著的优点:在验证身份的那一方,没有任何办法可以拿到用户的私钥,即使获得了那台机器的root权限。验证信息只能使用一次----这意味着,也没有办法把这个验证信息用于在其他地方再次验证身份。
其次,公钥/私钥要比密码长的多,因而可以挫败通过穷举的方式破解的可能性。
典型的密码是8位字符,假设可以使用大小写字母、数字和特殊符号,可选的范围无非是96^8而已,我们不妨算它128^8。典型的私钥有2048个 bit,如果按7个来分组的话,有128^(2048/7)。当然,最高位和最低位一定是1,但向下取整,也有128^292种。
最后,除了吃点带宽之外,SSH口令穷举对于仅采用公钥/私钥验证的服务器安全不构成任何威胁。
通过适当的配置sshd,可以让其直接明确地告诉对方此处不支持口令验证,并且能够容易地将攻击者记录在案,并将数据反馈给防火墙来减少带宽的占用。
from https://blog.delphij.net/2010/07/ssh.html
--------------------------------------------------
http://linux.die.net/man/1/ssh-copy-id
http://www.harding.motd.ca/autossh/
--------------------------------------------------------------------------------------------------------------------
在 Freebsd 下用 autossh 自动登录ssh tunneling proxy server并可掉线重连


事实上,SSH tunneling 除了可以本地应用外,还可以放在服务器上,做成一个 ssh tunneling proxy server ,这样可以让更多的客户端来通过 server 来使用 proxy ,不必在每个客户端上都开启 ssh tunneling ,当然考虑到服务器的性质,还要让 ssh tunneling proxy server 做到自动启动及自动断线重连,而这篇文章就是探索如何实现这一目的。
安装 autossh

什么是 Autossh ( 主页:http://www.harding.motd.ca/autossh/ )

SSH的特性就是安全,如果一个连接长期闲置,那么就可能被利用,所以SSH服务端一般都会有一个超过Idle时间踢出的设置。不过像我们经常会用 SSH登陆到远程服务器上长时间的工作的,这个特性就非常不方便了。于是autossh,就是这么一个牺牲安全性,换取便利性的工具。

autossh通过建立另一个SSH连接来监视工作SSH连接,当工作连接断开的时候,能够自动发起重连。不过你得设置ssh-agent,否则,重连的时候还是会提示你输入密码的,这样就失去意义了。

不过,就算是重连,你正在做的工作也会因为失去连接登出而都被杀死的。这时候就该GNU screen登场了。在你ssh到远程服务器的时候,启动一个screen Session,screen可以让你在ssh失去连接的时候自动detach,然后重连上来的时候,只要用screen -D -R取回screen Session就可以了。而且,autossh自带了一个非常好用的script rscreen,已经完完整整的帮忙做好了这件事情,只要直接拿过来用就可以了。

安装

cd /usr/ports/security/autossh/
make install clean
rehash

测试用 autossh 建立一个 ssh tunneling

autossh -M 2000 -N -v -D 192.168.0.1:7070 riku@fbhost.com

制作启动脚本

以下这部分取消, autossh 断线后还需要手动输入密码,所以无法实现自动连接。

通过启用证书认证方式就不需要输入密码了,能够让 autossh 自动重新连接。

用 ssh-keygen 生成 ssh 证书,生成的时候不要输入 passphrase 密码,直接回车。

然后进入个人目录的 .ssh 目录中

cd ~/.ssh

复制以 .pub 为后缀的公钥文件中的内容,把这些内容粘贴到远程 ssh 帐号中的 ./ssh/known_hosts 文件中。

安装 expect 什么是 expect http://zh.wikipedia.org/zh-cn/ExpectExpect 是Unix系统中用来进行自动化控制和测试的软件工具,由Don Libes制作,作为Tcl脚本语言的一个扩展,应用在交互式软件中如telnet,ftp,Passwd,fsck,rlogin,tip,ssh等 等。该工具利用Unix伪终端包装其子进程,允许任意程序通过终端接入进行自动化控制;也可利用Tk工具,将交互程序包装在X11的图形用户界面中。安装 <code> cd /usr/ports/lang/expect make install clean </code>

建立 /etc/autossh.sh 脚本

#/bin/sh
/usr/local/bin/autossh -M 2000 -N -D 192.168.0.1:7070 riku@fbhost.com&

给执行权限

chmod +x /etc/autossh.sh

建立一个名为 sshtunneling.exp 的 expect 脚本。 <code> #!/usr/bin/expect -f # Expect script to supply root/admin password for remote ssh server # now connect to remote UNIX box (ipaddr) with given script to execute spawn autossh -M 2000 -N -v -D 192.168.0.1:7070 riku@fbhost.com # Look for passwod prompt expect “*?assword:*” # Send password aka $password send – “password\r” # 这里的 pwassowrd 改成你自已的密码 # send blank line (\r) to make sure we get back to gui send – “\r” expect eof </code> 试运行这个脚本。 <code> expect sshtunneling.exp </code>

试运行这个脚本。

/etc/autossh.sh

通过 netstat 查看 7070 端口是否打开,如打开的话说明 ssh tunneling proxy 已经建立好了。

netstat -a | grep 7070

编写 /usr/local/etc/rc.d/sshtunneling 脚本,让 ssh tunneling proxy 开机自动运行。

脚本内容

#!/bin/sh
#
# PROVIDE: utility
# REQUIRE: DAEMON
# KEYWORD: shutdown

. /etc/rc.subr

name="sshtunneling"
rcvar=`set_rcvar`
command="/etc/autossh.sh"

load_rc_config $name

#
# DO NOT CHANGE THESE DEFAULT VALUES HERE
# SET THEM IN THE /etc/rc.conf FILE
#
utility_enable=${utility_enable-"NO"}
utility_pidfile=${utility_pidfile-"/var/run/utility.pid"}

pidfile="${utility_pidfile}"

run_rc_command "$1"

在 /etc/rc.conf 加入下行

sshtunneling_enable="YES"

为 sshtunneling 加可执行权限

chmod +x /usr/local/etc/rc.d/sshtunneling

试运行该脚本

/usr/local/etc/rc.d/sshtunneling start

PS:如果在 linux 下还可以用 sshpass ( http://sourceforge.net/projects/sshpass/ ) 这个软件来进行自动登录 ssh ,但它只支持原生的 ssh 客户端。


参考文章

SSH login expect shell script to supply username and password http://bash.cyberciti.biz/security/expect-ssh-login-script/

Freebsd 手册:启动服务 http://www.freebsd.org/doc/zh_CN/books/handbook/configtuning-starting-services.html

from http://w.riku.me/freebsd/autossh
-------------------------------------------------------
ubuntu desktop下实现ssh自动重连

ubuntu下使用ssh的方法很多:

   1. openssh。一般linux系统都默认安装,直接在终端(terminal)下使用即可.
   2. PuTTY。图形化界面,无须命令行,更便于新手使用。

但两者都有一个明显的缺点:无法实现ssh断线后的自动重连。openssh是终端命令行模式,断了只能重打命令;PutTTY则自己明确说明了一点:为 了安全问题不保存密码,每次都要用户自己输入。初衷是很好,但从实际应用的角度,ssh掉线的频率比较高,每次都要重输是很累的。所以更好的解决办法 是:expect。

首先要获取该程序,终端(terminal)下输入:

    sudo apt-get install expect

完成后随便新建一个文本,这里暂定名称是:sshgfw。可以直接在终端(terminal)下输入:

    sudo gedit sshgfw

在文本中粘粘如下内容:

    #!/usr/bin/expect
    set timeout 60

    spawn /usr/bin/ssh -D 7070 -p port -l user yourserver.com
    # 这里的port为你远端主机的端口名,一般为22,有变动的话一般空间商会告知你,user为你自己的用户名,yourserver.com为你自己的服务器域名或ip
    expect {
    "password:" {
    send "password\r"
    #这里的第二个password改为你自己的密码
    }
    }
    interact {
    timeout 60 { send " "}
    }

再加上可执行权限,我们仍然在终端(terminal)下执行:

    chmod a+x sshgfw

如果你严格的按照我所说的做下来,那么现在在直接终端(terminal)下输入:

    ./sshgfw


脚本就应该自动运行起来了。现在这个脚本应该是在你的帐户下,多帐户操作的话也可以把这个文件复制到 /usr/local/bin 或 /usr/bin 等目录下,以方便本机所有用户都可以快捷的使用。
以上内容参考了互联网上的相关资料,但也经过自己的实际操作,略作改动。如还有问题请提出(不保证能解决。。。)。

好了,准备收工。

from http://blog.alwayst.info/ubuntu-achieve-ssh-automatic-re-connection
----------------------------------------------------------------------------
Linux上使用ssh翻墙脚本的使用教程:(原文

综述

操作系统:Linux (debian\ubuntu\opensuse\fedora)
浏览器:Firefox »
优点:A方案支持断线自动重连,B方案操作简单;智能判断网址并切换代理。

第一步A方案:安装并配置expect

在 debian/ubuntu 终端中输入 : apt-get install expect
在 opensuse 终端中输入:zypper in expect
在 fedora 终端中输入: yum install expect
安装完毕后新建一个文件,比如命名为 sshgfw , 将如下代码复制进去,并根据代码中的注释将部分代码修改为你自己的SSH帐号信息。
#!/usr/bin/expect
########################################### # 服务器地址(或IP) set SERVER “ ” # 服务器 SSH 端口号 set PORT “ ” # SSH 用户名 set USER “ ” # 密码 set PASSWD “ ” ########################################### set timeout 60 spawn /usr/bin/ssh -N -D 7070 -p $PORT -g $USER@$SERVER expect { “*(yes/no)*” { send “yes\r”} “password:” { send “$PASSWD\r” } } interact { timeout 60 { send ” “} } view raw This Gist brought to you by GitHub. 加上可执行权限 chmod a+x sshgfw, 然后就可以在它所在的目录 ./sshgfw 执行就行了。当然也可以把它复制到 /usr/local/bin 或 /usr/bin 等目录下,以方便本机所有用户都可以快捷的使用。
注:ssh 加上 -g (即在代码中的 ssh -D 7070 -g ) 可使局域网内其它机器使用我的机器做代理. 以我的情况为例:我在一个局域网内的 ip 为 192.168.1.16 , 当我联上服务器之后,我就可以使用 localhost:7070 做代理,同时我的局域网内的其它 ip 为 192.168.1.* 的机器,就可以用代理 192.168.1.16:7070 来穿墙啦。
打开终端,输入:ssh -D 7070 username@yourserver.com,回车;
输入密码后,回车,即可登陆。
------------------------------------------------------------------------------
autossh是个很方便的管理ssh连接的工具。但是出于安全性的考 虑,ssh连接一段时间后没有活动,就会自动断开。对于我们这些把ssh主要用做穿墙代理工具的同学,无疑是很不方便的。所以很多人都使用autossh 这个工具。autossh会运行一个ssh子进程,并每隔一段时间检测ssh连接的状态,当ssh进程意外退出或连接断开时,autossh会重启ssh 进程。如果你的ssh服务器使用的是密钥认证的方式,autossh可以很完美的工作。但问题来了,如果你不得不使用密码认证的方式呢?当你用 autossh登陆ssh服务器,输入密码,连接建立了,可以穿墙了!过了一会儿,ssh连接超时,自动断开。autossh也意识到了这一点,于是它重 启了一个ssh进程,连接上服务器,接下来 - 输入密码… autossh可是不会帮你再输入密码的。所以,在密码认证的情况下,autossh基本算是废了。这也就是我们要再造一个autossh的轮子的原因, 而且要比它更圆,能自动输入密码。
我的方案是使用 expect这个工具。expect可以读取程序的输出,分析输出的内容,与期望的输出进行对比,并模拟输入。如果你玩什么基于文本的MUD游戏,就可以 用它来来自动完成枯燥的练级过程。我们首先很自然的就想到,用expect脚本来给autossh输入密码。在我们的这个情景中,我们希望autossh 作为expect脚本的子进程,当脚本结束时,autossh也跟着结束。否则再次运行expect脚本,由于autossh还在后台,就会出现错误,除 非你手动结束它。但是经过实践,发现autossh有一个问题,当autossh的父进程被结束时,其自身并不会跟着结束,而是变成孤儿进程,被init 收养(Mac OS下是launchd)。这在应用中就比较麻烦了。所以我们跳过autossh,直接用expect来控制ssh,实现autossh的功能,也就是给 autossh再造一个轮子。
实现的expect脚本如下,或 直接下载:http://ivsays.appspot.com/media/agZpdnNheXNyDAsSBU1lZGlhGMllDA/autossh.sh?a=download
#!/usr/bin/expect --
#!/bin/sh
#
# autossh.sh
# SimpleSSHProxy
#
# Created by ivan on 10-9-10.
#
# This is another wheel of autossh built using expect.
# If you have to use ssh password authorizing,
# use this instead of autossh.
#
# WARNING: This script is NOT SAFE for your password,
# DON'T USE THIS IF YOU HAVE SECURITY CONCERNS!
#
# Usage: autossh.sh [foo] [foo] [bindingIP:port] [foo] [username] [remoteHost] [password]

# get arguments
set IPandPort [lrange $argv 2 2]
set username [lrange $argv 4 4]
set remoteHost [lrange $argv 5 5]
set password [lrange $argv 6 6]

while (1) {
set connectedFlag 0;
spawn /usr/bin/ssh -D $IPandPort $username@$remoteHost;
match_max 100000;
set timeout 60;
expect {
"?sh: Error*" 
{ puts "CONNECTION_ERROR"; exit; }
"*yes/no*" 
{ send "yes\r"; exp_continue; }
"*?assword:*" {
send "$password\r"; set timeout 4;
expect "*?assword:*" { puts "WRONG_PASSWORD"; exit; }
set connectedFlag 1;
}
# if no password
"*~*"
{ send "echo hello\r"; set connectedFlag 1; }
}
if { $connectedFlag == 0 } { 
close;
puts "SSH server unavailable, retrying..."
continue
}

while (1) {
set conAliveFlag 0;
interact {
# time interval for checking connection
timeout 60 {
set timeout 10;
send "echo hello\r";
expect "*hello*" { set conAliveFlag 1; }
if { $conAliveFlag == 1 } { 
# connection is alive
continue;
} else { break; }
}
}
}
close;
puts "SSH connection failed, restarting...";
}
将上面的代码保存为一个文本文件,如autossh.sh,chmod加上x属性,使用方法为:
autossh.sh [foo] [foo] [bindingIP:port] [foo] [username] [remoteHost] [password]
其中的 foo 参数并无实际意义,可以用任何字符串代替,保留其的目的是使此脚本与autossh的参数调用方法兼容。
这 个脚本可以自动输入ssh密码,并且实现autossh的主要功能,即ssh连接的断线检测和重连,但是无法实现ssh进程意外退出时重生ssh进程。当 ssh进程意外退出(比如你手动杀掉)脚本进程也就退出了。不过这种情况实在比较难以遇到,所以也算是合格。如果实在需要ssh进程的重生,可以考虑这么 一种思路:再用一层expect脚本来包裹这个脚本进程,在外层脚本中实现进程的重生功能,(这个用while循环和wait命令是非常容易实现的)这个 问题就留给有心的读者自己研究吧。
from http://ivsays.appspot.com/2010/09/10/Build-a-wheel-of-autossh-using-expect.html
----------------------------------------------------------------------------------------
我在用 SSH 密钥来进行电脑与服务器的授权工作,这样更自动化而且比将密码直接写入文本的文件里要安全多了。先打开一个终端,根据一下步骤进行密钥配置:

[jonolumb@jonoxps .ssh]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/jonolumb/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/jonolumb/.ssh/id_rsa
Your public key has been saved in /home/jonolumb/.ssh/id_rsa.pub
The key fingerprint is:
h7:10:49:46:ab:2t:3b:a3:36:2z:15:56:d4:f2:b7:3d jonolumb@jonoxps

请注意,配置时密码要留为空白。

将生成的 /home/jonolumb/.ssh/id_rsa.pub 的内容复制到远程服务器目录下,具体位置是:
~/.ssh/authorized_keys
要保证远程的 authorized_keys 和 本地的 id_rsa 文件的权限均为 700。
这样就可以自动登录到远程服务器了.
-------------------------------------------------
在linux desktop下,不输入密码登录ssh server的方法
1、打开Terminal(终端),输入“ssh-keygen -t rsa”,等待一下,然后连续三次回车确认。
2、输入“cd ~/.ssh”进入.ssh文件夹。
3、输入“cp id_rsa.pub authorized_keys”生成authorized_keys。
4、把authorized_keys传你服务器的.ssh文件夹下,输入“scp authorized_keys 你用户名@服务器:~/.ssh”。 例:“scp authorized_keys nie@demo.dreamhost.com:~/.ssh”,其间会问你是否继续连接,输入“yes”,然后会让你输入密码。
如果没有.ssh文件夹,自行创建。输入命令“ssh 你用户名@服务器”,然后输入密码进入服务器,例:“ssh nie@demo.dreamhost.com”,进入后输入“mkdir .ssh”创建.ssh文件夹,再输入“chmod go-w .ssh”,然后输入“logout”退出连接,到此.ssh文件夹创建完成。
5、输入“ssh -D 7070 你用户名@服务器”看看是不是不需要输入密码即可登录你的ssh server了?例:“ssh -D 7070 nie@demo.dreamhost.com”。
from http://todaym.com/2010/05/iphone-ipod-touch-mac-ssh-connection-automatic-login.html
------------------------------------------------------------------------------------
原生 SSH

在终端下输入如下命令

ssh username@ssh-hostip -D 127.0.0.1:7070

把其中的 username , hostip 替换成你自已的内容。

第一次运行此命令需要输入 yes 来接受证书,最后输入 SSH 密码。如果你不想每次都输入密码的话,可以采用证书认证方式。

终端下运行 ssh-keygen 命令来生成证书,直接按三次回车无需输入任何内容。

ssh-keygen

进入 SSH 目录

cd ~/.ssh

打开 id_rsa.pub 文件,复制里面的所有内容。

然后通过 ssh 连接到远程 ssh 主机,进入 ~/.ssh 目录,打开 authoried_keys 文件,把刚才复制于 id_rsa.pub 的内容粘贴进去。

这样下次再建议 ssh tunneling 的时候就无需输入密码了。

最后你可以建立一个 shell 脚本文件,这样不必每次输入命令了,方便使用。


AutoSSH
AutoSSH 的使用方法和 SSH 类似,只是它提供了断线自动连接功能,这样就不必每次重新输入命令了。
安装
sudo apt-get install autossh
使用
autossh -M 2000 -N -v  username@hostip -D 127.0.0.1:7070 (i don't know how to use this tool)

Plink
Plink 最大的好处在于可以指定密码,不必采用证书方式就可以不输入密码建立链接了。
安装
sudo apt-get install putty-tools
使用
plink -N -v username@hostip -D 127.0.0.1:7070 -pw password
把其中的 username , hostip , password 替换成你自已的内容。

gSTM (this tool is good)
gSTM 是管理ssh tunnel的图形化工具.它全称为 Gnome SSH Tunnel Manager ,是一个 Linux 上用来管理 SSH Tunnel 的图形管理工具,方便用户建立多个 SSH Tunnel。
主页: http://sourceforge.net/projects/gstm
Ubuntu 下安装,
sudo apt-get install gstm
打开 gSTM,按下图进行配置,把相应的内容替换成你自已的数据。




最后到主界面进行Start就 OK 了。
from http://wiki.wowubuntu.com/blog/ubuntu_ssh_tunneling

------------------------------------------------------------------
Sshmenu - Linux 上的 SSH 连接管理工具
主页:http://sshmenu.sourceforge.net

下载及安装介绍:http://sshmenu.sourceforge.net/download/deb_repo.html

Ubuntu 安装

you can add this entry to your /etc/apt/sources.list:
deb http://sshmenu.sourceforge.net/debian stable contrib

Import our repository key:
gpg --keyserver subkeys.pgp.net --recv-keys 4CC00851
gpg --export --armor 4CC00851 | sudo apt-key add -

And then install the relevant package and dependencies with these commands:
sudo apt-get update
sudo apt-get install sshmenu-gnome

如何添加到菜单上? http://sshmenu.sourceforge.net/setup/ (i don't know how to add the tool to the menu)
-----------------------------------------------------------------------------

PAC Manager: Ubuntu 上强大的 SSH 帐号管理工具,可取代 SecureCRT

对于在 Windows 上经常需要远程管理 Linux 服务器的 SA 们来说,也许会觉得 SecureCRT 非常好用,因为它是一个强大的 SSH 帐号管理工具,而且可以记住密码,但这个是收费软件。而现在如果你想在 Ubuntu 上也需要这样一款软件的话,那么 PAC Manager 也许正是你要寻找,它是一款非常不错的替代品,而且完全开源免费。
主页: http://sites.google.com/site/davidtv/   (this is a good tool)
PAC Manager 基于 Perl/GTK 构建,目前最新版本为 2.4 。
功能:
  1. 支持远程及本地宏命令。
  2. 支持 EXPECT 批处理。
  3. 支持代理。
  4. 支持集群连接。
  5. 支持标签或窗口。
  6. 批量帐号管理等等。
截图:


安装:Ubuntu 用户可以到以下地址下载 DEB 安装包
https://sourceforge.net/projects/pacmanager/
http://www.gnomefiles.org/app.php/PAC_Manager
快速安装:
sudo apt-add-repository "deb http://archive.getdeb.net/ubuntu lucid-getdeb apps"
sudo apt-get update -y
sudo apt-get install pac -y
from http://wowubuntu.com/pac.html
---------------------------------------------

SSH Tunneling On Android

If you want to have a secure browsing environment or just want to access your home network securely without exposing extra services to the internet and without the mess that comes with setting up and maintaining a VPN server, ssh tunneling is your rescuer. In this post, I’ll tell you how to setup an ssh tunnel to your home network easily. Also look for some bonus tips at the end
This article assumes that you have already installed and setup a ssh server (you can probably use openssh). Also, it assumes that the ssh server is accessible from the internet (i.e. you have appropriately forwarded the port on which ssh server is running). I’d also recommend that if you do not have a static IP for your home network, then sign up for a dynamic DNS service (I use dyndns.org) so that you can access your home network easily by using a domain name (e.g. myserver.dyndns.org) from outside.
Now, here is a step by step guide on what to do on your Android Phone (I’m doing this on a Nexus one but should be same for you as well):1. Install an app called “connectbot” from the android marketplace. It is a FREE ssh client for android.
2. Open it and add the IP (or dynamic domain name as suggested above) and the port on which ssh server is running to the bottom and connect.
Android SSH Tunnel 1
2. Once connected, press the menu button and select the icon which says “Port Forwards”
Android SSH Tunnel 2
3. On this screen you can configure the ports to be used for tunneling. As you can see I already have my firefly server port configured for music streaming over itunes’ DAAP protocol. Now, you can press “menu” button and click on “Add ports” and go to step 4.
Android SSH Tunnel 3
4. You will see the dialog box as shown below. Here you can configure mainly two types of ports.
Android SSH Tunnel 4
4a) First is for services that you want to access already running on your home network. e.g. in my case, I have a firefly media server (mt-daapd) running on a port “12345″ and I want to access this just like I was on LAN over my home wi-fi. In such a case, select “type” as “Local”, source port as , say “56000″ and destination as “ip:port” where ip is the your home local area IP of the machine on which the server is running (My server runs on router itself, which has IP 192.168.1.1) and the port is the actual port on which server is running (e.g. 12345 as we mentioned above). After doing this, just open the respective client app on your phone which wants to connect to this server and enter “127.0.0.1″ as the ip and “56000″ as the port to connect to and it will connect to server as if you were on your home network even over 3G or your office wi-fi.
4b) Secondly, you can use this tunnel to route all traffic to internet through home connection. For this, choose the type as “dynamic” and source port as, say, ” 56001″. You don’t need to select a destination port here because any traffic that comes over this tunnel will be routed back to the internet using the destination ip and port as desired, e.g., specified in a browser’s address bar.
Bonus: As I promised above, here is the bonus. For media streaming, you can use mt-daapd or firefly server on your home network, especially on a router like asus wl-500 or any other hackable router with custom firmware. For more info about how to set it up, you can check these posts: Latest Firefly server for your router and firefly sqlite error solution.  For android side things, install the “DAAP Client” app from the market place and click on “Add server” option and follow step 4a as mentioned above. And there it is, your own music streaming service anywhere in the world, over edge/3G or any other network :)
原文:http://tech.shantanugoel.com/2010/08/02/ssh-tunneling-android.html
-----------------------------------------------------------------------------------------------------

SSH for Win32

[TODO: Add SftpDrive scp client.]
  • F-Secure by F-Secure Corporation (formerly Data Fellows, Ltd.) is a proprietary, binary-only SSH client. Includes scp. ssh protocol v. 2.0 & 1.5.
    http://www.europe.datafellows.com/products/cryptography/f-sshtt.htm
    ftp://ftp.zedz.net/pub/crypto/programs/ssh/f-secure/
  • SSH Tectia is SSH Communications Security, Ltd.'s proprietary SSH client & server. Includes scp. ssh protocol v. 2.0.
    http://www.ssh.com/products/client-server/
  • Portable OpenSSH by The OpenBSD Foundation is an SSH client & server. Recent versions build cleanly on Win32 using Cygwin, thanks largely to Corinna Vinschen's work. Client & server. C source & binary under the BSD licence. Requires Eric Young's OpenSSL. Requires Cygwin DLLs from http://sources.redhat.com/pub/cygwin/. ssh protocol v. 2.0 & 1.5.
    ftp://ftp.openssh.com/pub/OpenBSD/OpenSSH/portable/
    ftp://sources.redhat.com/pub/cygwin/release/openssh/
    ftp://mirrors.rcn.net/pub/sourceware/cygwin/release/openssh/
    and other Cygwin mirrors.
  • "SSHWindows" = Portable OpenSSH for Win32 by Michael Johnson is an SSH client & server. C source & binary under the BSD licence. This is a Cygwin build installable with the Cygwin libraries (included) but without a full Cygwin installation. ssh protocol v. 2.0 & 1.5.
    http://sshwindows.sourceforge.net/
  • Dropbear by Matt Johnston is a small SSH2 client & server, primarily but not exclusively intended for embedded use. Source & binaries under an MIT/X11 licence. (On Win32, requires and runs under Cygwin.) Supports X11 forwarding, and authentication-agent forwardingfor OpenSSH clients. Includes scp and other traditional SSH functions. ssh protocol v. 2.0
    http://matt.ucc.asn.au/dropbear/dropbear.html
  • Sysax Multi Server by Codeorigin, LLC is an SSH2 & telnet client & server, including support for http, https, ftp-ssl, and sftp. SSH server can manage its own user authentication database, and offers Web-based administration. Supports generating SSL certificates. Proprietary software w/30-day eval. download, binary-only. ssh protocol 2.0
    http://www.sysax.com/
  • SecureCRT by Van Dyke Technologies, Inc. is an SSH & telnet client. Proprietary software w/30-day eval. download, binary-only. Supports file transfers; server must run an ftpd. (Recent versions include a "vcp" command-line utiltiy to do scp.) Supports session-logging. Supports port-forwarding. ssh protocol v. 2.0 & 1.5.
    http://www.vandyke.com/products/SecureCRT/
    ftp://ftp.zedz.net/pub/crypto/programs/ssh/secure_crt/
  • SecureFX by Van Dyke Technologies, Inc. is an SSH file-transfer client. Proprietary software w/30-day eval. download, binary-only. Does ftp tunnelled over SSH, and also serves as a regular ftp client. ssh protocol v. 2.0.
    http://www.vandyke.com/products/securefx/
  • VShell by Van Dyke Technologies, Inc. is an SSH server. Supports ssh, scp, sftp, port forwarding/tunneling. User ACLs for fine permissions control, supports chrooting, configurable "trigger" actions. Proprietary, binary-only. ssh protocol v. 2.0.
    http://www.vandyke.com/products/vshell/
  • VCP by Van Dyke Technologies, Inc. is an scp client for the command line. Proprietary, binary-only. ssh protocol v. 2.0.
    http://www.vandyke.com/products/securecrt/vcp.html
  • Entunnel by Van Dyke Technologies, Inc. is a port forwarding/tunneling utility. Supports smart cards, X.509 certificates, winsock and SOCKS proxies. Proprietary, binary-only. ssh protocol v. 2.0.
    http://www.vandyke.com/products/entunnel/
  • TTSSH (TeraTerm SSH) by Robert O'Callahan is an extension to T. Teranishi's TermTerm Pro. Source & binaries, under a free-usage licence. Files can be copied over SSH tunnel using zmodem. Supports RSA-key-based authentication and port-forwarding. Note that you will need both TeraTerm Pro and TTSSH. ssh protocol v. 1.5.
    http://www.zip.com.au/~roca/ttssh.html
    http://hp.vector.co.jp/authors/VA002416/teraterm.html
    ftp://ftp.zedz.net/pub/crypto/programs/ssh/ttssh/
  • TeraTerm Pro Web by Ayera Technologies, Inc. is an ssh client based on T. Teranishi's TermTerm Pro telnet client and Robert O'Callahan's TTSSH extension, adding SSH2 protocol support and improved port-forwarding. Proprietary, binary-only. ssh protocol v. 2.0 & 1.5.
    http://www.ayera.com/teraterm/
  • Poderosa by Daisuke OKAJIMA and colleagues is a tabbed terminal network client for MS-Windows, supporting SSH1, SSH2, telnet, SOCKS proxy, SSH2 port forwarding, ssh key generation. Open source under Apache License v. 2.0. ssh protocol v. 2.0 & 1.5.
    http://en.poderosa.org/
  • Xshell by NetSarang Computer, Inc. is a tabbed terminal emulator network client for MS-Windows, supporting SSH1, SSH2, SFTP, telnet, rlogin, and serial connections. Supports X11 forwarding and port forwarding. Proprietary, binary-only. ssh protocol v. 2.0 & 1.5.
    http://www.netsarang.com/products/xsh_detail.html
  • E-Term32 by DCSI Solutions is an SSH1, SSH2, telnet, and serial terminal client. Proprietary, binary-only. ssh protocol v. 2.0 & 1.5.
    http://www.dcsi.com/
  • Kermit95 from the Kermit Project at Columbia University is an SSH1, SSH2, telnet, rlogin, SOCKS4 proxy, port forwarding, and X11 forwarding client. Proprietary, source available. ssh protcol v. 2.0 & 1.5
    http://www.columbia.edu/kermit/k95.html
  • AbsoluteTelnet by Brian Pence is a telnet/SSH1/SSH2 and SOCKS proxy client. Supports passthrough printing, X11 and port forwarding. Does zmodem over ssh for file transfers. Proprietary, binary-only. ssh protcol v. 2.0 & 1.4
    http://www.celestialsoftware.net/telnet/
  • PuTTY by Simon Tatham is an SSH & telnet client. Source & binaries under a free-usage (MIT) licence. pscp, Tatham's separate command-line executable for scp, is at the same site. (See also entry for Secure iXplorer.) v. 0.52 and up support port-forwarding, and also introduces psftp, Tatham's separate command-line client for the SSH2-family sftp protocol. ssh protocol v. 2.0 & 1.5.
    http://www.chiark.greenend.org.uk/~sgtatham/putty.html
    http://the.earth.li/~sgtatham/putty/latest/
  • FiSSH by Mass Confusion (Timothy Chen) is an SSH client. Source & binaries available under a mostly-free licence. ssh protocol v. 1.5.
    http://www.massconfusion.com/ssh/
    http://pgpdist.mit.edu/FiSSH/
    ftp://ftp.zedz.net/pub/crypto/programs/ssh/fissh/
  • AppGate Client. Proprietary. Optional Java-based front-end GUI. Authentication methods include ACE/SecurID, Entrust, iD2, and Telia EID. ssh protocol v. 2.0 & 1.5.
    http://www.appgate.com/products/appgate_client.html
  • PenguiNet is Silicon Circus's SSH & telnet client. Proprietary, binary-only shareware/adware. No scp, but it is planned for the next version (v. 1.1). ssh protocol v. 1.5.
    http://www.siliconcircus.com/penguinet/
  • ZOC by EmTec (Markus Goemmel & Markus Schmidt) is an SSH & telnet client. Proprietary software w/30-day eval. download, binary-only. ssh protocol v. 1.5 (and "1.99" compatibility mode on 2.0 & 1.5 protocol combo-server setups).
    http://www.emtec.com/zoc/
  • TinyTERM Plus by Century Software is an ssh client. Proprietary software w/"demo" version. ssh protocol v. 1.5.
    http://te.censoft.com/products/tinyterm_plus.html
    ftp://ftp.censoft.com/download/windows/
  • SecureNetTerm by InterSoft International, Inc. is an ssh/telnet client. Proprietary, binary-only software, with "eval" download. ssh protocol v. 2.0 & 1.5.
    http://www.securenetterm.com/html/securenetterm.html
  • QVT/Term by QPC Software is an ssh/telnet client. Proprietary, binary-only software. ssh protocol v. 1.5.
    http://www.qpc.com/prod02.htm
  • Metro State SSH is a from-scratch implementation by unknown authors at Metro State College of Denver. IDEA and RSA encryption only, for now. Requires OpenSSL libraries from http://www.openssl.org/. Binary & source. BSD licence. ssh protocol v. 1.5.
    http://cs.mscd.edu/MSSH/
  • SecureShell by Pragma Systems is an SSH server & client. Proprietary, binary-only. No scp. ssh protocol v. 1.5.
    http://www.pragmasys.com/SecureShell/
    ftp://ftp.pragmasys.com/pub/pragm
  • Mocana Embedded SSH Server by Mocana Corp. is a small, fast ssh server primarly for embedded use. Also does telnet-ssl, tunneling, port forwarding. Extensible. Proprietary, binary-only software. ssh protocol v. 2.0
    http://www.mocana.com/ssh.html
  • Mocana Embedded SSH Server by Mocana Corp. is a small, fast ssh client primarly for embedded use. Also does telnet-ssl, tunneling, port forwarding. Extensible. Proprietary, binary-only software. ssh protocol v. 2.0
    http://www.mocana.com/sshclient.html
  • Iconfident SSH by Icon Labs is a small, fast SSH server and client primarily for embedded use. Proprietary software available in source and binary forms. ssh protocol v. 2.0 & 1.5.
    http://www.icon-labs.com/products.asp
  • SFTPPlus by Pro:Atria Ltd. is an SSH1/SSH2 server & client for Win32 and sundry Unix platforms. Also does FTP, HTTP, FTPS (FTP over SSL) and HTTPS file transfer. Proprietary, binary-only. ssh protocol v. 1.5.
    http://www.sftpplus.com/
  • CVS by Gordon Chaffee is a patched variant of the standard CVS 1.9.10 utility, capable of using SSH transport. You must set the CVS_RSH environment variable to the pathname of ssh.exe. Source patch & binary. Licence unstated.
    ftp://bmrc.berkeley.edu/pub/winnt/util/cvs.exe
    http://bmrc.berkeley.edu/people/chaffee/patches/patch-cvs-1.9.10
  • PortForwarder, a general TCP-port forwarder using code from OpenSSH/OpenSSL for SSH transport, by Fujio Nobori. Source code. BSD-style licence. Does not include terminal support. ssh protocol 1.5.
    http://www.fuji-climb.org/pf/
  • U/WIN by AT&T is not an SSH package in itself, but rather a toolkit for recompiling Unix applications to Win32. Ylönen's SSH will compile cleanly. U/WIN binaries are available gratis for non-commmercial usage. Proprietary.
    http://www.research.att.com/sw/tools/uwin/
  • Cygwin by Red Hat Software, Inc. (formerly Cygnus) is not an SSH package in itself, but rather a toolkit for recompiling Unix applications to Win32. Ylönen's SSH will compile cleanly. Tools are variously under the GNU General Public Licence, the MIT X Licence, or public domain.
    http://sources.redhat.com/pub/cygwin/
  • Secure iXplorer by Lars Gunnarsson is a graphical front-end for Simon Tatham's pscp (Putty scp) utility (included). GNU General Public Licence for the standard version; proprietary licensing for the "Pro" one. Delphi5 source code or Win32 binaries.
    http://i-tree.org/ixplorer.htm
  • PSCopy by Lars Gunnarsson was his first effort at a graphical front-end for Simon Tatham's pscp (Putty scp) utility, providing a simpler, dialog-based user interface than its successor, Secure iXplorer. GNU General Public Licence. Delphi5 source code or Win32 binaries.
    http://i-tree.org/pscopy.htm
  • WinSCP2 is Martin Prikryl's graphical scp client. Win32 binary. Proprietary gratis-usage licence. ssh protocol 1.5 and 2.0.
    http://winscp.vse.cz/eng/
  • Sysax FTP Automation by Codeorigin, LLC is an sftp, ftp-ssl, and ftp tool script and schedule recurring file-transfer tasks. Scheduler can trigger on change to a monitored folder. Proprietary software w/30-day eval. download, binary-only. ssh protocol 2.0
    http://www.sysax.com/
  • Telneat is Kosta Scheglov's ssh/telnet client. Binary only. Licence unstated (proprietary by default). ssh protocol v. 2.0 & 1.5.
    http://telneat.lipetsk.ru/
  • SmartFTP by SmartSoft, Ltd. is a full-featured ssh/telnet terminal client. Supports various terminal types, xterm mouse extensions, Unicode, remote printing, extensive keyboard mapping including Emacs support, numerous public-key certificate types, Kerberos v5, RSA SecurID, more. Proprietary, binary-only. ssh protocol 2.0.
    http://www.smartftp.com/features/ssh/
  • Network Simplicity SSH-Scan by Mark Bradshaw is a Perl script to scan networks up to class C size to find all operating SSH servers and report their versions. Licence unstated (proprietary by default).
    http://www.networksimplicity.com/openssh/
  • Net-SSH-W32Perl CPAN Perl module by Scott Scecina and Benjamin Tilly. Win32 access to Tilly's Net-SSH-Perl module for ssh/scp client access. Source code (script) under a free-usage licence. ssh protocol v. 2.0.
    http://search.cpan.org/doc/SCOTTS/Net-SSH-W32Perl-0.05/lib/Net/SSH/W32Perl.pm
  • Shaolin Secure FTP by Joe Testa is a graphical front-end to Portable OpenSSH's sftp functions. Requires a Cygwin Win32 version of Portable OpenSSH. C++ source code under the GNU General Public Licence. ssh protocol 2.0.
    http://www.shaolinsecureftp.com/
  • ShellGuard by NetComposite, Ltd. is an ssh/telnet/scp client. Includes key-generator, port-forwarding. Proprietary, binary-only. ssh protocol v 2.0 & 1.5.
    http://www.shellguard.com/
  • WinSSHD ssh2 server by BitVise Ltd. supports ssh, sftp, scp, and port-forwarding/tunneling. Proprietary, binary-only. ssh protocol v. 2.0.
    http://www.bitvise.com/winsshd.html
  • Tunnelier ssh2 client by BitVise, Ltd. supports ssh, port forwarding/tunneling. Proprietary, binary-only. ssh protocol v. 2.0.
    http://www.bitvise.com/tunnelier.html
  • CuteFTP Pro by GlobalScape, Inc. is an ftp, ftps, http, https, and S/Key client, and also includes sftp support. Proprietary, binary-only. ssh protocol v. 2.0.
    http://www.cuteftp.com/products/cuteftppro/
  • FileZilla is Tim Kosse's graphical ftp and sftp client. C++ source code and Win32 binary under the GNU GPL. ssh protocol v. 2.0.
    http://sourceforge.net/projects/filezilla
  • sftp is David John Pinson's port of Brian Wellington's sftp to Cygwin, an ftp client that operate over any SSH tunnel, or over rsh. Should not be confused with the sftp protocol in the ssh 2.0 protocol suite, which is a newer protocol and incompatible. C source & binaries under the GNU General Public Licence.
    http://www.dpinson.com/software/sftp/
  • WS_FTP Pro ftp and ftp-ssl client by Ipswitch, Inc. now also supports sftp. Proprietary, binary-only. ssh protocol v. 2.0.
    http://www.ipswitch.com/Products/WS_FTP/
  • ShellGuard by Indochine House Ltd. d/b/a NetComposite (formerly Kosta Schegloff's Telneat) is a telnet, SSH, scp, port-forwarding, and keygen client. Proprietary, binary-only. ssh protocol v. 2.0 & 1.5.
    http://www.shellguard.com/
  • SecEx by Bytefusion Ltd. is an SSH, scp, and sftp client. Proprietary, binary-only. ssh protocol v. 2.0 & 1.5.
    http://www.bytefusion.com/products/ens/secex/index_secex.htm
  • Red Bird SFX by Kandmtech, LLC is a graphical shell for sftp and scp file transfers (copy or move). Also supports crypto key generation and remote manipulation of owner/group/rights metadata, ability to type in filenames to fetch non-browseable files, per-site stored preferences/credentials. Proprietary, binary-only. ssh protocol v. 2.0 & 1.5
    http://kandmtech.com/knmtech/
  • COPSSH by Tevfik Karagülls is a Cygwin port of OpenSSH with an optional proprietery graphical front-end utility (COPSSH Control Panel). Win32 binary under the MIT/X11 licence. ssh protocol v. 2.0 & 1.5.
    http://www.itefix.no/copssh/
  • Reflection for Windows Desktops by WRQ is a terminal emulator client (using the OpenSSH codebase), along with the package's primary role of being a Web-based management server and task-management toolkit. Proprietary, binary-only -- except of course that the OpenSSH client code is BSD-licensed. ssh protocol v. 2.0 & 1.5.
    http://www.wrq.com/products/reflection/win/
  • Reflection X by WRQ is an X11 display server, incorporating SSH support using the OpenSSH codebase, a Kerberos client, an ftp client, and so on. Proprietary, binary-only -- except of course that the OpenSSH client code is BSD-licensed. ssh protocol v. 2.0 & 1.5.
    http://www.wrq.com/products/reflection/pc_x_server/


Historical Section

These early OpenSSH ports have been obsoleted by the official Cygwin port (for those who don't mind installing all of Cygwin) and Michael Johnson's SSHWindows port (for those who do mind). Those below are thus deprecated.
FROM: http://linuxmafia.com/ssh/win32.html
---------------------------------------------------------------------
Introduction

If you want to access remote servers securely from Windows 9x, NT, ME, 2000 or XP and don't want to pay for programs that are freely available for UNIX-like platforms, you may find this document useful. It describes free SSH implementations for Windows.

Although this document concentrates on Windows-specific implementations, much of the content, particularly relating to Port Forwarding and Authorized Keys, applies to any SSH implementation, regardless of the platform. VPN technologies, (including IPSEC), are discussed in passing, but these are not the main focus.

Email me, fitz@jfitz.com, if you find better implementations, or if you think there's anything I can add here. Please note that I will only include references to products that are available free of charge, and I have a strong preference for open source implementations.

For more links to SSH tools for Windows, (and Mac), I'd recommend trying the OpenSSH Windows/Mac pages: http://www.openssh.com/windows.html, or http://www.openssh.com/macos.html.


What is SSH?

SSH is a protocol that uses public key cryptography to transfer data securely over insecure networks. At the core of most SSH implementations are the "ssh" and "scp" commands.

"ssh" and "scp" are "secure" versions of the UNIX "rsh" and "rcp" commands, (which in turn are a bit like the more familiar "telnet" and "ftp" programs). The "ssh" command provides command-line, (non-GUI), access to a remote server. "scp" allows files to be copied to/from a remote server. Both programs use the SSH protocol to establish a secure connection and to encrypt all data passing between the client and the server.


What is "Port Forwarding" or "Tunneling"?

In addition to the direct access provided by the "ssh" and "scp" commands, the SSH protocol includes a feature called "Port Forwarding", or "Tunneling". This can be used to provide secure access to other services that do not normally encrypt data during transmission.

For example, to receive email, many email programs use the (unencrypted) POP3 protocol to connect to a mailserver on port 110. If we can SSH to the mailserver before downloading our mail, we can configure the SSH session to "forward" port 110 through the encrypted SSH link. Now, if we configure our email client to connect to port 110 on our local machine it will in fact be connecting to the remote mailserver, but all the data, (i.e. our incoming email), will be transferred over the encrypted SSH link.

If we also forward port 25, (which normally handles SMTP, the outgoing email protocol), then both incoming and outgoing email will be encrypted.

If you are mainly interested in securing your Windows email client, you could try jumping straight to my step-by-step guide to configuring a PuTTY SSH client for port forwarding email traffic.

Any number of ports can be forwarded in a single SSH session. For example, we could also forward port 80, (HTTP), to provide secure access to a corporate webserver. In effect, it is usually possible to create a pretty good approximation to a VPN, (Virtual Private Network), just by forwarding a handful of common ports, and using scp, (or WinSCP), to transfer files. In fact, a VPN is roughly equivalent to an SSH session where everything is being forwarded over a single secure channel.


Should I use SSH or a VPN?

If you are trying to decide between SSH and a VPN, I find that SSH is generally appropriate in situations where occasional remote access is needed to specific services, (for example, checking email, downloading files). If persistent access to a wide range of services is required, (for example, working exclusively on a corporate network while telecommuting), then a VPN is probably a better choice.

One of the problems with a VPN is that both the client and server need to be customized for the VPN to work, whereas most modern UNIX-like servers will provide SSH access by default when a user account is established, (so only the client PC needs configuring). A second problem is that traditional VPNs tended to be difficult to configure correctly, particularly on the server-side. However, solutions such as OpenVPN, (http://openvpn.net), are much easier to install and configure than many of the more traditional, IPSEC-based VPN solutions, so if you have administrative (root) privileges on the server it may be worth exploring OpenVPN. A VPN may require more work initially to get running on the server, but it will ultimately provide more flexibility on the client.


PuTTY

PuTTY, (and its file transfer utility, pscp), are excellent Windows ssh/scp implementations, and are a piece of cake to get up and running.

Download putty.exe and pscp.exe here: http://www.chiark.greenend.org.uk/~sgtatham/putty/, and you're ready to go. These programs are not zipped and do not require any installation.

When you run PuTTY, a configuration screen is presented first. It's a good idea to play with the configuration until you get colors, fonts and other settings that suit you. You can then give the session a name and save it, so it's easy to restore these settings next time you run PuTTY, (just double-click the stored session name). This process can be a little awkward because you need to exit and restart PuTTY to update a stored session, but once you have a good set of settings saved, you can use that session as a template to create other stored sessions for different host machines.

To help you get up and running with PuTTY, I've created a step-by-step guide to configuring a "typical" PuTTY session, (including port forwarding for incoming/outgoing email). You can check it out here: http://www.jfitz.com/tips/putty_config.html

When you first connect to a new machine using PuTTY or pscp, they will give you a message to indicate that they don't recognize the machine. Choose "OK" to add the machine to the list of known hosts and to continue connecting.

PuTTY works a bit like an xterm. If you highlight text with the mouse it is automatically copied to the clipboard. A right-click of the mouse will paste the copied text at the command-line cursor position. Right-click anywhere on PuTTY's Title Bar, (or left-click on the PuTTY icon in the top left corner), to access a menu where the current session settings can be changed.

To remove PuTTY automatically, run "putty -cleanup", (without the quotes). To do the job manually, delete the files you downloaded and use regedit to remove all the keys under
HKEY_CURRENT_USER->Software->SimonTatham->PuTTY.


WinSCP

WinSCP provides an easy-to-use graphical interface to "scp" functionality. It creates an SSH link to the remote server, then displays local and remote files in "Explorer-like" windows. Copying files securely to/from the remote machine is as simple as dragging and dropping, (or cutting and pasting), files in the WinSCP windows.

As of version 3, WinSCP also supports SFTP, ("secure ftp"). Unless you specifically need to use SFTP, it's probably as easy to stick with SCP -- the basic WinSCP functionality handles many of the issues that SFTP was designed to address.

You can download WinSCP here: http://winscp.net/eng/

WinSCP starts with a configuration screen and can save session settings in a manner that is very similar to PuTTY.

As of version 3, WinSCP includes a "Cleanup" option that allows you to remove any possibly sensitive settings that may have been created on your computer. With version 2, to remove WinSCP delete WinSCP2.exe and, to clean up the registry, use regedit to remove all the keys under
HKEY_CURRENT_USER->Software->Martin Prikryl->WinSCP 2.

WinSCP is released under the GPL. The source code is available for download with the application. WinSCP is partly based on PuTTY code, (it is usually pretty up-to-date -- check the WinSCP site for version details).


pscp

pscp is a companion program of PuTTY. It is a pretty straightforward Windows implementation of scp. It's a command-line program only, so you need to run it in an MS-DOS window.

The basic format of a pscp command, (or any scp command for that matter), is:

pscp myusername@remotehost:remotefilespec localfilespec

...to download from remotehost to your local machine, or:

pscp localfilespec myusername@remotehost:remotefilespec

...to upload to remotehost from your local machine.

Type pscp with no arguments for a list of other parameters that can be supplied on the command line.


Tera Term Pro/TTSSH

Another good terminal emulation package that supports SSH is Tera Term Pro. You can download it here: http://ttssh2.sourceforge.jp/

Tera Term Pro comes with a regular Windows setup program. As with PuTTY, I'd recommend changing the terminal settings to suit your preferences. Save the setup as teraterm.ini to replace the defaults.

The original version of Tera Term Pro is still available here: http://hp.vector.co.jp/authors/VA002416/teraterm.html. However, this version requires the extension TTSSH to enable SSH, and the original download site for TTSSH, (http://www.zip.com.au/~roca/ttssh.html), isn't accessible any more.

If you happen to have the original teraterm/ttssh and want to install it, unzip the ttssh file in the same directory that Tera Term Pro is installed in. This adds a program called ttssh.exe. Run this program in place of Tera Term Pro itself, (ttermpro.exe), and you will then have SSH available as an option during connect. Additionally, you will find that some SSH options are added to the Setup menu. You may wish to change the defaults so that SSH, (on port 22), is the default connection method.

There is also a version of Tera Term available from the company Ayera Technologies. This is based on the original Tera Term code, but I'm reluctant to recommend it because the revised source code is not freely available.

Tera Term Pro with TTSSH used to be the best free SSH implementation for Windows, but, in my opinion at least, recent versions of PuTTY have surpassed them for ease of use and improved functionality. You may wish to try both and draw your own conclusions.


Command line/X Windows - Cygwin/OpenSSH

If you're happiest working in a UNIX-like command-line environment, and are already familiar with the "ssh" and "scp" commands, you may want to try Cygwin, (http://www.cygwin.com/). Cygwin is a pretty complete GNU based, (i.e. UNIX-like), environment for Windows.

If you don't want/need the full Cygwin UNIX-like environment, OpenSSH for Windows, (http://sshwindows.sourceforge.net/), is basically a "cut-down" version of Cygwin which includes command line ssh/scp/sftp functionality. It also includes ssh/sftp servers, and it has a fairly straightforward Windows installation program. (Note that OpenSSH for Windows replaces the older, and no longer maintained, Network Simplicity OpenSSH server solution, http://www.networksimplicity.com/openssh/.)

If you do choose Cygwin, and you are comfortable working in the X-Windows environment, in addition to the rich selection of GNU command-line programs, (including sshd, ssh, scp and sftp), there are also Cygwin ports of XFree86, (http://cygwin.com/xfree/), KDE, (http://kde-cygwin.sourceforge.net/), and Gnome, (http://cygnome.sourceforge.net/). While this is no substitute for dual-booting with a good Linux distro or BSD release, it is handy for doing quick X-Windows work on a server without needing to reboot your Windows machine. I haven't used Cygwin's X-Windows tools extensively, but I have noticed that the quality and stability seems to be improving with each new release.


Known Hosts

The "known hosts" list contains the public keys of host machines that you "trust" when using ssh or scp. All implementations of ssh/scp, (including PuTTY, WinSCP and TTSSH), will give warnings if you are connecting to a new machine that is not in the list of known hosts. In addition, they will refuse to connect if the host's public key does not match the stored value.

PuTTY stores the list of known hosts in the registry, under the key:

HKEY_CURRENT_USER->Software->SimonTatham->PuTTY->SshHostKeys.

WinSCP also stores the known hosts in the registry, under the key:

HKEY_CURRENT_USER->Software->Martin Prikryl->WinSCP 2->SshHostKeys.

Tera Term Pro stores its list of known hosts in the following file:

C:\"Program Files"\ttermpro\ssh_known_hosts

(assuming the program was installed in the default folder).

If a host machine's public key is legitimately changed, (as part of an upgrade for example), you will need to remove the old key from the file, (or the registry in the case of PuTTY or WinSCP), to successfully connect to that host. You should, of course, be 100% sure that the key was genuinely changed, and that this is not a hacker's machine masquerading as the host -- this is why these keys are stored and checked in the first place.


Automatic login

With any of the installations covered so far we can only establish an SSH connection provided we supply a password each time. It is possible to automate SSH connections by generating "passphrase-less" secure keys and modifying our connection settings to use the new keys. In general, I would only recommend this procedure if you have a specific requirement for automating file transfers, and you clearly understand the security implications.

Keys can be generated on the Windows client-side, using PuTTYGen, or on the server-side, using ssh-keygen. Either program will generate a public key file and a private key file. Different key file combinations can be generated for different SSH protocol versions. If you specify a blank "passphrase", then only the key files will be required to authenticate the connection, thereby allowing unattended connections. (If you include a passphrase you will benefit from a "doubly-secure" authentication, based on both the key and the passphrase.)

To use the keys, save the key files in a secure location on the client machine. Then copy the contents of the public key file into the file $HOME/.ssh/authorized_keys, (SSH protocol version 1), or $HOME/.ssh/authorized_keys2, (SSH protocol version 2), on the server machine. Finally, modify the PuTTY, WinSCP or TTSSH session details so that it uses the saved private key file, (making sure it also uses the correct protocol for the specified key). You will find the option to specify the Private Key File under the SSH settings.

Assuming you've got the right files in the right places, and the correct session settings, when you attempt to connect you should find that you can connect without supplying a password or passphrase.

If you are using Cygwin and the command-line ssh/scp versions, you can check the man pages for ssh to determine where you need to save your key files so that the ssh and scp commands will connect without requiring a password/passphrase.

This "passphrase-less" approach is reasonably secure, provided access to the client machine is restricted. However, if someone manages to steal your private key file, (which might not be that difficult on most Windows machines), your server account will be fully compromised.


SSH Servers

The following is a brief introduction to SSH server software for Windows.

Cygwin, (http://www.cygwin.com), includes a port of the OpenSSH server software. Cygwin is basically a GNU, (UNIX-like), subsystem that runs on 32-bit Windows. To get SSH support for Cygwin, install the "openssh" package in addition to the basic Cygwin packages.

If you have any problems installing and configuring Cygwin "by hand", you could also try http://sshwindows.sourceforge.net/. This implementation basically wraps Cygwin's OpenSSH port in a package that includes a standard Windows installation program.

If you have concerns about running open source secure services, such as OpenSSH or OpenVPN, on Windows, the main alternative is the IPSEC functionality that comes built-in to Windows 2000 servers. IPSEC is fully supported by Microsoft, and Windows-compatible implementations are also available for most *nix. This seems intuitively more secure, since it involves fewer components that are not integral parts of the Windows O/S.

You could also use Windows Terminal Services. This has built-in encryption and has the advantage that it gives you GUI access. You might want to use this in conjunction with IPSEC if you have any concerns about the Terminal Services encryption algorithms.

If you prefer open source solutions, it is still possible to get secure remote GUI access to a Windows server using freely available software. VNC, (http://www.realvnc.com/), provides remote GUI access to Windows machines, and it uses predictable port assignment, so a VNC client session can be port-forwarded over an SSH link provided the Windows server is running an SSH server, (in addition to the VNC server).

I believe it is also possible to port-forward a Terminal Services client session over SSH -- the server appears to use port 3389 by default according to the following Microsoft support article: http://support.microsoft.com/default.aspx?scid=kb;en-us;150543.


Old Versions of this Document

The previous version of this document, (which you may find useful if you are using older versions of Windows SSH utilities), is available here: http://www.jfitz.com/tips/ssh_for_windows_doc_version2.html.


Summary of Links in this Document

* TTSSH is no longer available.
FROM http://www.jfitz.com/tips/ssh_for_windows.html
-----------------------------------------------------------------------------------------------------------------------------

Tired of typing your password into SSH all the time? Yes, you can apply common, open-source tools to do this for any application of SSH. Isn't open software cool! Read-on...
General SSH questions, a bit of background on SSH and specifically Public Key Cryptography, and versions of SSH clients can be found in my mini-SSH FAQ.

Creating and Using SSH Identities

The first step in secure, password-free SSH is to create an SSH identity. An SSH identity is a private/public key pair, which are similar in functionality to to PGP keys, or SSL keys and SSL certificates. The public key of the identity pair will be placed on the remote servers to which you wish to connect and the private key will remain on the client or local machine. When you connect from your client, the ssh program will offer to use identity-based authentication for each key it has available. If the server sees a corresponding public key on its end, it tells the client to prove that it has the private key, which is does by a mathematically rigourous means that we can ignore at this time.
We can do this with either OpenSSH or with PuTTY.

Configuring OpenSSH to use Identities

Installing OpenSSH

If you are running on a UNIX box without SSH (many do by default), have your system administrator build and install OpenSSH. A version of this is installed by default on most Linux platforms, but you or your system admistrator should update it as there are often security-related patches made available on the OpenSSH web site.
If you are running on a Windows platform and use CYGWIN, you should already have SSH installed. Again, make sure you keep up with new releases of the SSH package (via the CYGWIN installer) for security.

Configuring OpenSSH

  1. Create the identiy-key pair:
    cd ~/.ssh
    ssh-keygen
    This creates your private/public key pair: (~/.ssh/id_rsa and ~/.ssh/id_rsa.pub). The program will ask you for a passphrase to encode your private key; be sure to use a good passphrase of more than 10 or so characters. If you choose not to use a passphrase, you will not have to implement the ssh-agent or putty-agent steps below, however I do not recommend this; Without a passphrase, your private key can be easily read by anyone and may be used to impersonate you on any server where you place your public key.
    Instead of RSA, you may use DSA (-t dsa) either is fine, though I would not recommend using RSA1 for security reasons.
  2. Copy the public key to the remote server:
    scp ~/.ssh/id_rsa.pub user@remote.host:pubkey.txt
    ssh user@remote.host
    mkdir ~/.ssh
    chmod 700 .ssh
    cat pubkey.txt >> ~/.ssh/authorized_keys
    rm ~/pubkey.txt
    chmod 600 ~/.ssh/*
    exit
    Be sure to replace user@remote.host with the appropriate username and host. This copies your public key to the remote server machine. Public keys are those with the .pub extension. You need to do this for each server into which you wish to login via SSH without a password. Alternatively, you could now copy the ~/.ssh/authorized_keys file to other systems to allow access from the local system. Also, if you have multiple keys, you can add the public key of each pair to the authorized_keys file, either by appending to the file or using a text editor. If you use cut and paste to copy the key, make sure each key entry is a single line in the file. Remember, the keys to add are always the public keys (from files with the .pub extension).
  3. Test the remote public key:
    ssh user@remote.host
    <enter-private-key-passphrase-at-prompt>
    exit 
    This is a test -- This time, instead of your password on the remote host, SSH should prompt you for the passphrase for your private key.
  4. Start the ssh-agent:
    Now we get to the meat of this document and figure out how to avoid typing either a password or a passphrase every time...
    eval `ssh-agent`
    This starts the ssh-agent, which is a process which runs in the background and listens for "requests" from ssh clients needing your private key. The output of ssh-agent is a set of environment variables which need to be eval-ed in order for future ssh clients to know that there is a server out there. Do not start more than one instance of ssh-agent.
  5. Add your private key to the agent's cache:
    ssh-add
    <enter-private-key-passphrase-at-prompt>
    This adds your private key(s) to the list of keys held by ssh-agent. ssh-add will ask you for the passphrase of each key it is adding to the agent's pool. Note that this need only be done once after you start the ssh-agent daemon.
  6. Test the connection again:
    ssh user@remote.host
    exit
    This is a test -- This time you should not have to type any passwords or passphrases as ssh should get your private key from the agent daemon.
That's all there is to setting up ssh and ssh-agent to use public-key encryption and avoid entering your password multiple times a day. Any application that uses SSH should no longer require passwords. All that remains is to configure CVS to use SSH.
You should know that ssh-agent stores your private key(s) in memory in the clear (read: unencrypted) to give to ssh clients that request it. Note that the mechanisms by which ssh-agent talks to ssh are based upon UNIX sockets and UNIX system permissions protect those against unauthorized access, so you need not worry about this. There is some question about the security of this mechanism under CYGWIN on Win32 platforms, but I feel the risks are not greater than the benefits, especially if you are the only person with access to your Windows box. Just lock your screen when you are not present - common sence.
One other tweak one can make: Realize that by using this "manual" approach of starting the agent and evaluating the results in your shell, only sub-shells of the current shell will know about the running ssh-agent. An alternative approach that I use is to run a short script that starts the agent daemon if it is not already running and sets the appropriate environment variables.
  1. Setup an automated start-agent script:
    First, click here for my sssha script. It is a BASH shell script, so if you use a different login shell, you will have to modify it. Once you download it, place it in your ~/.ssh/ directory and add this to your ~/.bashrc configuration script, presumably at or near the end:
    # setup ssh-agent, if appropriate
    if [ -f "$HOME/.ssh/sssha" ]; then
       source $HOME/.ssh/sssha
    fi 
Finally, if you are truly paranoid, make sure to kill your ssh-agent when you are done using any machine on which you have started one. This can be accomplished most simply with ssh-agent -k.

Configuring PuTTY to use Identities

Installing PuTTY (Windows only)

First, you need to fetch PuTTY which is available from here: http://www.chiark.greenend.org.uk/~sgtatham/putty/ or a Google search on PuTTY should find it too. The installer is a fairly typical windows installer, so just go ahead and run it. The defaults are perfectly acceptable.

Configuring PuTTY

PuTTY Configuration
Figure 1: PuTTY Configuration
Once you have PuTTY installed, run PuTTY and you will be presented with a PuTTY Configuration window that looks something like that in Figure 1. Adjust each Category of settings as follows:
  1. Session
    • Check: SSH
  2. Connection
    • Auto-login username: username
      with your username
  3. Connection » SSH
    • Preferred SSH protocol version: 2
  4. Connection » SSH » Auth
    • Check: allow agent forwarding
    • [ you will come back here later to specify your Private key file for authentication ]
Go back to the Session category, click on the Saved Session named Default Settings and click Save. These are now your default PuTTY options.
Test the settings by typing the name of a remote host into the Host Name box and clicking Open. You should be prompted for your remote password and eventually get a shell window.
Go ahead and close that shell by typing exit.

Generating your Public/Private Keys

PuTTY Key-Generator
Figure 2: Generating your key
With PuTTY configured, you can now generate your public/private key. On the Windows START menu, where PuTTY shortcuts were installed, should be a shortcut for PuTTYgen. You should see a window like that in Figure 2.
  1. Check: SSH2 RSA (or SSH2 DSA, but NOT SSH1 RSA)
  2. Click: Generate
    While PuTTYgen is generating your key, create some "entropy" by moving the mouse around in the empty area of the window.
  3. Enter a Key Passphrase
    Make sure it is a good passphrase of more than 10 or so characters. If you choose not to use a passphrase, you will not have to use the PuTTY-Agent (below), however I do not recommend this; Without a passphrase, your private key can be easily read by anyone and may be used to impersonate you on any server where you place your public key.
  4. Click: Save Private Key
    Select a place to put your keys such as your home directory; name it something like PuTTY-Private.ppk
  5. Click: Save Public Key
    Save it to the same directory as the private key, presumably; name it something like PuTTY-Public.pub
  6. Create your authorized_keys file by coping the text from the Public Key for pasting into authorized_keys text-box into a file, again presumably to the same directory, named something like openssh-key.pub

Configure the Server's ~/.ssh/authorized_keys file

You now need to copy your public key to the remote SSH server and update one setting in your PuTTY configuration:
  1. Store your openssh-key.pub on the remote server in your remote ~/.ssh/authorized_keys file:
    1. Open Command/Shell Prompt by typing cmd in the Windows Run dialog or by starting a CYGWIN shell.
    2. Copy Public Key to Server: at the command prompt, enter:
      [ CMD: ]
      pscp c:\path\to\openssh-key.pub username@cvs.server.com:openssh-key.pub
      or
      [ CYGWIN: ]
      scp /cygdrive/c/path/to/openssh-key.pub username@cvs.server.com:openssh-key.pub
      ...where c:\path\to\openssh-key.pub specifies the location of the key file created in step two, and username@cvs.server specifies your user name on the CVS server and the hostname of the CVS server. You may be prompted to confirm the legitimacy of the host, and you will be prompted to enter your password for the CVS server.
    3. Connect using PuTTY: if necessary, run the putty program, entering the name of the remote cvs server.
    4. Configure the Key on the CVS Server: after logging into the CVS server, enter the following commands to place your public key into the remote ~/.ssh/authorized_keys file:
      mkdir ~/.ssh
      chmod 700 .ssh
      cat ~/openssh-key.pub >> ~/.ssh/authorized_keys
      rm ~/openssh-key.pub
      chmod 600 ~/.ssh/*
      exit 
      You can also copy/paste, ftp, email or transmit your public key to the remote server by any means you find convenient. Just put the contents in the ~/.ssh/authorized_keys file, ensuring that what you paste is only one (long) line.
  2. Configure PuTTY to use the Private Key: Open PuTTY again; when the configuration window opens:
    • Open the Connection » SSH » Auth configuration category
    • Set the location of your PuTTY-Private.ppk file in the Private Key File for Authentication box
    • Return to the Session configuration category
    • Select and save your settings into the Default Settings
Test the settings by typing the name of the remote host into the Host Name box and clicking Open. You should be prompted the passphrase of your private key rather than for your remote password; close the resulting shell window by typing exit.

Starting the PuTTY-Agent (Pageant)

Run the pageant program from the START menu. This will load the PuTTY Authentication Agent into the Windows System Tray; it appears as a little computer with a "secret agent hat". PuTTY-Agent is a process which runs in the background and listens for "requests" from PuTTY clients needing your private key.
When PuTTY-Agent starts, it doesn't know about your private keys by default. Right-click the Pageant icon in the Windows System Tray. Select Add Key. Navigate to the directory where you saved the public and private keys in the previous step, and select the file PuTTY-Private.ppk. Pageant will prompt you for the passphrase of the key.
Now you are basically done. Restart PuTTY again to test the settings one last time; enter the name of the remote host into the Host Name box and clicking Open. You should NOT be prompted the passphrase of your private key nor your remote password; close the resulting shell window by typing exit.

Auto-Start PuTTY-Agent Upon Login

Pageant can automatically load one or more private keys when it starts up, if you provide them on the Pageant command line (i.e. in a shortcut). If you copy the standard Pageant shortcut, append the location of your key(s) to the Target: line. It might look something like this:
C:\PuTTY\pageant.exe d:\main.key d:\secondary.key
If the keys are stored encrypted, Pageant will request the passphrases on startup.
If you place that new shortcut in your Startup folder, it should be loaded automatically when you login to Windows.

Using PuTTY Keys for OpenSSH and vice-versa

If you already have keys used for OpenSSH or for PuTTY, you may use those keys in the other application, but you need to go through an import or export step using PuTTYgen.
  1. First, open PuTTYGen again...

To import a OpenSSH key into PuTTY:

  1. In PuTTYgen, select: Conversions » Import Key
  2. Browse to your private OpenSSH key and select Open.
    You should be required to enter your private key passphrase.
  3. Click: Save Private Key
    Select a place to put your keys such as your home directory; name it something like PuTTY-Private.ppk
  4. Click: Save Public Key
    Save it to the same directory as the private key, presumably; name it something like PuTTY-Public.pub
Everything else should proceed as before, including using PuTTY-Agent (Pageant), but be sure to tell PuTTY about your new Private Key as above.

To export a PuTTY key for OpenSSH:

  1. In PuTTYgen, select: Conversions » Load Private Key
  2. Browse to your private PuTTY key and select Open.
    You should be required to enter your private key passphrase.
  3. Select: Conversions » Export OpenSSH Key
    Select a place to put your keys such as your home directory; name it something like openssh-key.
  4. To save the public key, follow the same instructions for creating the openssh-key.pub file as above.
Everything else should proceed as before, including using PuTTY-Agent (Pageant), but be sure to copy your openSSH key to the server, as above.
----------------------------------------------------------------------------
Go straight to the Quick Selection Guide
Introduction
Terminal emulators provide a telnet or SSH connection to UNIX like servers. Commercial products can emulate a wealth of terminal types, provide GUI face-lifting etc. All very nice, but this can leave the emulator feeling sluggish. Free implementations are more focused on the job at hand — providing a fast no-frills connection.
There is no shortage of candidates so I am presenting a couple of mature offerings followed by some modern projects.
Most free products only offer a narrow range of screen emulations, typically vt100, linux or xterm. As a full time support analyst, I considered support for the following features as my essential criteria.
  • Configureable function key sequences
  • Configureable answerback message
  • Local printing
Without these accessing or supporting legacy green screen systems is likely to be problematic.
Discussion
Dave's TelnetDave's Telnet was the only package to offer all three essential criteria—albeit some manually. It offers emulation for linux/xterm/vt100/vt220/vt320/vt440.
Dave’s Telnet replaced my commercial product for a week with only a couple of minor points. Copy and paste functions seemed clunky and it failed to connect to one hostname, I had to specify the IP address.
PuTTYPuTTY is another very popular mature package, but only offers xterm emulation.
It does not appear to support an answerback message or configurable function keys. However in the case of function keys this may not be applicable to xterm emulation. PuTTY has been incorporated into many related projects.
Both choices are maintained, but new releases are infrequent.
The following two packages I reviewed just missed a recommendation, but remain on my watch list.
Poderosa provides a modern tabbed environment offering vt100/xterm/kterm emulations and the ability to extend with plugins. It offers no obvious support for my criteria, but proved robust as a basic terminal emulator with a useful context menu available from right click. Another interesting feature is auto complete based on previously typed commands. This may be of interest to system administrators or those requiring basic remote access. Requires .NET v2 to be installed. Unfortunately this project seems to have gone the way of the Dodo with no updates since 2006. This is a great shame for a project that could easily have become my hands down winner over time.
Terminals is a more general remote access package including a vt220 terminal emulator. It provides a tabbed environment offering the ability to connect using telnet/Remote Desktop/VNC and others. It also provides over a dozen network analysis options, including ping, traceroute and whois. Again no obvious support for my criteria. I encountered stability issues using Windows 2000, although no definitive list of supported versions is given. This may be of interest to system administrators looking after a wide range of machine types. Currently being actively developed.
Quick Selection Guide

Dave's Telnet    Rating 9 of 10  Gizmo's Top Pick

Pros Offers all three essential criteria, emulation for linux/xterm/vt100/vt220/vt320/vt440
Cons Copy and paste functions seemed clunky, have to specify the IP address.
Developer Home Page http://dtelnet.sourceforge.net/
Download link http://sourceforge.net/projects/dtelnet/
File Size 124.8 KB   Version 1.2.4   License Type Open Source Freeware (includes program code)   Installation Requirements 95/98/Me/NT/2000/XP/Vista
Portable Portable
from http://www.techsupportalert.com/best-free-telnet-ssh-terminal-emulator
--------------------------------------------------------------------------------
用SSHPASS实现非交互式自动登录SSH SERVER

ssh原本为了安全性,只能在ssh server后再手动输入密码,而不能像下面的命令那样:
echo -n 'PASSWORD' |sudo -S ls /

要不只能用“密钥对”的方式自动登录,再要不就用“expect”写脚本来自动登录,不过刚刚发现了一个小软件:sshpass
在Ubuntu 10.04下面是没有安装expect和sshpass的,既然这样,我还不如只装上sshpass,还不用写expect脚本呢!

用命令 sudo apt-get install sshpass 就可以装上sshpass包了,下面是sshpass的用法:
sshpass -p 'PASSWORD' ssh icyomik@ssh.sshcenter.info

注:sshpass支持“-f”选项,可以从文本文件读取密码,而不用出现在命令行。
因为是私有机器,所以不怕所谓的不安全,要是用“密钥对”的话,虽然安全但太麻烦,何况在某些机器上不方便保存密钥。
FROM http://icyomik.appspot.com/20101014/52001
----------------------------------------------------
windows server下,建立ssh server

1、http://Cygwin.com,下载Cygwin。
2、在线安装,选择NET-SSH+SSL。
3、用鼠标右键单击我的电脑 –>属性 –>>高级 –>>环境变量,
A.在系统变量框中新建变量名为:CYGWIN,变量值为:ntsec tty 的变量。
B.编辑path变量,在原变量值后加上以分号分隔的C:\Cygwin\bin字符串。
4、进入/bin 目录,
ssh-host-config -y
5、使用bitvise,生成KEY,再按OpenSSH格式导出。
6、
mkdir /home/***/.ssh
7、建立authorized_keys
把第五部导出的key用记事本打开写入authorized_keys。
8、chmod 644 /home/***/.ssh/authorized_keys.
OK!Have fun!from http://1945fa.de/archives/146
----------------------------------------------------
连接SSH服务器刚刚离开一会就断 开,不 得不需要反复连接服务器, 为了使SSH服务器可以保持足够的连接时间,大家可以按以下方法设置:基于安全的理由,假设用户连线到 SSH Server 后闲置,SSH Server 会在超过特定时间后自动终止 SSH 连线。以下是设定终止连线时间的方法:
1、打开 /etc/ssh/sshd_config 文件,找到一个参数为 ClientAliveCountMax,它是设定用户端的 SSH连线闲置多长时间后自动终止连线的数值,单位为分钟。+ [1 q' |6 [8 A
2、假设这一行最前面有#号,将那个#号删除,并修改想要的时间。
3、修改后保存并关闭文件,重新启动 sshd:2 p* l2 |& b- U1 [  l6 h1 o5 m+ y* I
/etc/rc.d/init.d/sshd restart

------------------------------------------------------------------------------------
ssh服务器的密钥验证
 关掉ssh是不可能的,但服务器24小时开机,总有一天会被别人穷举到密码的,为了把安全级别提高到更高地步,今天将服务器上ssh服务验证方式 更改为密钥验证。 一来解决了暴力破解的安全漏洞,二来简化了我管理N多服务器输入密码的颇烦之处(N多服务器不可能用一个密码吧? 反正我是不会那样滴!)。
      ssh的验证方式有键盘交互、主机验证和密钥验证,默认前两种都可用。我的简介就是如此简单,预知详情,请“自己看ssh的manual”
      今天有空,就将整个操作流程的详细步骤叙述如下:
1、首先创建rsa或dsa密钥对: 
$ ssh-keygen

$ ssh-keygen -t dsa

bpxyz@gateway ~/.ssh $ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/bpxyz/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/bpxyz/.ssh/id_rsa.
Your public key has been saved in /home/bpxyz/.ssh/id_rsa.pub.
The key fingerprint is:
10:c2:02:4a:1a:62:df:d3:ca:a9:24:d9:26:d3:fc:98 bpxyz@gateway

提示“Enter file in which to save the key (/root/.ssh/id_rsa):”是指生成的密钥对存在什么地方叫什么名字,默认就行。
提示“Enter passphrase (empty for no passphrase):”是指是否使用密码来保护生成的密钥对里的私钥,如果不使用密码保护,任何人得到私钥都可以直接使用他。
在当前用户家目录的.ssh目录里生成两个文件:id_rsa和id_rsa.pub(或者是id_dsa和id_dsa.pub),前者是私钥,后者是公钥。 公钥需要放到要登录的远程服务器上,私钥自己保留。
2、将公钥拷贝到远程服务器上,并改名为authorized_keys
bpxyz@gateway ~/.ssh $ scp id_rsa.pub bpxyz@192.168.6.3:~/.ssh/authorized_keys

为了安全,登录到远程服务器,修改公钥的权限(该步骤为可选)
bpxyz@gateway ~/.ssh $ chmod 600 authorized_keys

至此我们就已经可以使用密钥来登录远程服务器而不需要输入用户密码了!
但如果在生成密钥对的时候使用了密码保护密钥,那在使用私钥的时候,需要输入密钥的保护密码:
Enter passphrase for key '/root/.ssh/id_rsa': 
但是直接使用系统用户名和密码仍然可以登录系统,那我们来更改远程服务器sshd的配置,拒绝使用系统用户名和密码登录。
3、更改远程服务器ssh配置。我的实例是使用openssh,所以更改/etc/ssh/sshd_config中如下参数
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePam no

意思即不使用密码验证方式和挑战式验证。

OK,使用密钥来验证用户的sshd服务器就配置好了。 以上方式只适合于linux到linux,很多人估计跟我一样,客户机使用putty或其他win版的ssh客户端,他们的配置稍微不一样点点,但原理都一样,以下简介使用putty实现密钥对验证用户的步骤.

1、下载完整的putty软件包,我们使用软件包中的puttygen.exe生成密钥对。运行puttygen.exe,
点击在新窗口中浏览此图片
2、选择要生成的密钥对的类型和长度,点击Generate,然后将鼠标放到“key”框中随意移动(产生随机数据),待到第一次的进度条走完后,生成密钥对。
3、生成密钥对后,可以修改密钥对的“Key comment”(密钥说明)、“Key passphrase”(密钥的使用密码)。一切ok后,点击“Save public key”和"Save private key"分别保存公钥和私钥。公钥放到远程sshd服务器上,私钥供putty连接远程sshd服务器时使用。
使用任意方式将刚刚生成的公钥拷贝至远程sshd服务器上对应用户家目录里的.ssh目录内,改名为authorized_keys,同样最好是设置权限为600。
4、运行putty,在左侧树状分类目录里选择“Data”,在右侧窗口中“Auto-login username”处填写自动登录用户名
点击在新窗口中浏览此图片
5、再在左侧树状分类目录里选择“Auth”,在右侧“Private key file for authentication:”处填写刚刚使用puttygen.exe生成的私钥,
6、登录远程服务器,你会发现没输用户密码我们就已经登录到远程sshd服务器了(当然如果私钥受密码保护,还要输入私钥的使用密码)。


怎么样?还算简单噻?
现在是不是觉得还是不够方便? 每次使用有密码保护的私钥的时候,要输入私钥的保护密码,跟输入系统用户密码没太大差别,别急,putty想到这点了!
运行putty软件包里的“pageant.exe”,
这是私钥代理,帮你缓存你输入过的私钥密码,只要不退出pageant,就不需要重复输入私钥的保护密码,方便了噻。
pageant的使用方法很简单,点击pageant的图标,
点击“Add key”,将你要使用的密钥导入,然后输入密钥的保护密码就ok了,

以后再使用对应的私钥都不需重复输入私钥密码了。


总结:
1、ssh使用的密钥有两种 rsa和dsa,对应两种不同的加密算法,前者弱点,后者要优秀点,所以dsa被使用在ssh2版本中。
2、密钥对在客户机上生成和在服务器上生成是一样的。
3、服务端验证用户的公钥文件名可以通过更改/ets/ssh/sshd_config里的AuthorizedKeysFile关键字来更改,默认为.ssh/authorized_keys。
4、客户端用于验证的私钥文件名可以通过更改/etc/ssh/ssd_config里的IdentityFile关键字来更改,
默认为:~/.ssh/identity、~/.ssh/id_rsa和~/.ssh/id_dsa。
5、openssh生成的私钥不能直接给putty使用,用putty包里的puttygen转换一下即可。
---------------------------------------------------------------------------

利用 PuTTy 通过证书认证,登录ssh服务器

我们需要为 SSH 用户建立私钥和公钥。首先要登录到需要建立密钥的账户(比如root账户)下,运行:
# ssh-keygen
这里,我们将生成的 key 存放在默认目录下即可。建立的过程中会提示输入 passphrase,这相当于给证书加个密码,也是提高安全性的措施,这样即使证书不小心被人拷走也不怕了。当然如果这个留空的话,后面即可实现 PuTTy 通过证书认证的自动登录。
ssh-keygen 命令会生成两个密钥,首先我们需要将公钥改名留在服务器上:
# cd ~/.ssh
# mv id_rsa.pub authorized_keys
然后将私钥id_rsa从服务器下载到本地机器,并删除掉服务器上的 id_rsa 文件。
服务器上的设置就做完了,下面的步骤需要在客户端电脑上来做。首先,我们需要将 id_rsa文件转化为 PuTTy所支持的格式:ppk格式。这里我们需要利用 PuTTyGEN.exe这个工具:
点击 PuTTyGen 界面中的 Load 按钮,选中本地机器上的id_rsa 文件,输入 passphrase(如果有的话),然后再点击 Save PrivateKey 按钮,这样 PuTTy所接受的私钥文件(.ppk文件)就做好了。
打 开 PuTTy,在 Session 中输入服务器的 IP 地址,在 Connection->SSH->Auth 下点击 Browse 按钮,选择刚才生成好的私钥文件(.ppk文件)。点击底部的 Open 就可以通过证书认证,登录到服务器了。如果有 passphrase 的话,登录过程中会要求输入 passphrase,否则将会直接登录到ssh服务器上,非常的方便。(不错,我设置成功
-------------------------------------------------------------------------------------------

How to make SSH work faster?

You may be work­ing on SSH ev­ery­day, login­ing in and out, switch­ing re­mote ma­chines, change work lo­ca­tions (if you are work­ing on a lap­top), over and over. Each time you lo­gin in­to a ma­chine, you have to wait for the com­mand prompt for sev­er­al sec­onds, in­put us­er name and pass­word and kick your­self in­to the shell fi­nal­ly. Don’t you think­ing it’s too time con­sum­ing to re­peat the same ac­tions? For me, I can not bear in­put­ing the same pass­word ev­ery­day. Here are some tricks to boost your pro­duc­tiv­i­ty when work­ing with SSH.

Au­to Lo­gin

OpenSSH has a great fea­ture “key-based au­tho­riza­tion” which us­es RSA/DSA key pair to do au­tho­riza­tion in­stead of pass­word. With the help of it, lo­gin can be done au­to­mat­i­cal­ly.
Here are the steps:
  1. Cre­ate ssh key pair, if you have’t one. Check ~/.ssh. If you find a fine with name id_dsa.pub or id_rsa.pub, you are done since the key pair is ready to use. Oth­er­wise, cre­ate it sim­ply by typ­ing ssh-keygen and fol­low­ing the in­struc­tions. Keep in mind that there are two kinds of key pairs, RSA or DSA. I al­ways use RSA. You can choose one on your own. If you choose RSA with oth­er op­tions as de­fault, you will get id_rsa and id_rsa.pub in ~/.ssh. The for­mer file is the pri­vate key and lat­ter one is the pub­lic key.
  2. Make sure your ~/.ssh is pri­vate. I want to em­pha­size that here that the pri­vate key, i.e. id_rsa, is the equiv­a­lent with your pass­word since peo­ple who can ac­cess this file can lo­gin the re­mote ma­chine eas­i­ly as they got your pass­word! So make it pri­vate first.
    chmod 700 ~/.ssh
  3. Trans­fer your pub­lic key to the re­mote ma­chine which you want to lo­gin au­to­mat­i­cal­ly. SCP may be a pre­ferred way:
    scp ~/.ssh/id_rsa.pub user@remote.machine.com:~/my_key.pub
  4. Ap­pend your pub­lic key to the ~/.ssh/authorized_keys on the re­mote ma­chine.
    cat my_key.pub >> ~/.ssh/authorized_keys
  5. Done! Check whether you can lo­gin in­to the re­mote ma­chine au­to­mat­i­cal­ly by sim­ply type
    ssh user@remote.machine.com
    on your lo­cal ma­chine. If it works, re­move the pub­lic key on the re­mote ma­chine.
  6. For geek­ers who’d like to do it in one-line fash­ion, here it is:
    cat ~/.ssh/id_dsa.pub | ssh -l user remote.machine.com ‘cat >> ~/.ssh/authorized_keys’

Even Faster

Even au­to lo­gin is set up, in some cas­es you have to wait for sev­er­al sec­onds be­fore the shell prompt bombs out. Still frus­trat­ing, right? In some worse cas­es, you have wait more than 10 sec­onds or even longer! Why? Each time you con­nect a re­mote ma­chine, sshd would like to use your IP ad­dress to ap­ply re­verse DNS lookup to de­ter­mine your host­name. If the DNS serv­er goes slow, it may take sec­onds to re­turn the re­sults. The longer the lookup takes, the longer you have to wait.
Two tricks can be ap­plied to solve this prob­lem:
  1. Ed­it /etc/hosts on the re­mote ma­chine and add the IP ad­dress of your lo­cal ma­chine to it with an ap­pro­pri­ate host­name. So if you lo­gin the sys­tem, your IP ad­dress is re­solved lo­cal­ly, which is def­i­nite­ly faster.
  2. Dis­able DNS lookup on the re­mote ma­chine. Ed­it /etc/ssh/sshd_config and add one line:
    UseDNS no
    Restart the sshd serv­er then. If ev­ery­thing goes well, you will see the save of time.
Both tricks re­quire root priv­i­lege. If do not have root ac­cess, ask your ad­min­is­tra­tor to help you.

Trou­bleshoot­ing

Use ssh -v or ssh -vvv to out­put de­bug in­for­ma­tion and di­ag­nose the prob­lem.
--------------------------------------------------------------------------------

What you'll need

  • An SSH server to act as your proxy.
    "SSH server" sounds frightening, but it's just another computer off-site that allows you to login into it via SSH. Most web hosts allow SSH access to the server; or you can set one up at home with free software.
  • An SSH client on the computer you're using.
    Mac and *nix machines have SSH built right in at the command line. Windows users can set up OpenSSH with Cygwin. Here's more on installing the free OpenSSH with Cygwin.

How proxies work

In a nutshell, what you're doing with a proxy is setting up a middle-person between you and the internet. Using the proxy, your browser hands off web page requests to the proxy server, which handles the request and fetches the page for you from the internet. The web site actually thinks the request is coming from the proxy server, not your computer, which is a good way to obscure your originating IP address.
Additionally, the connection between your computer and the proxy happens over SSH, an encrypted protocol. This prevents wifi sniffers at the coffee shop from seeing what you're doing online.
For the more visual readers in the house, a (quick and dirty) diagram:

Now let's get down to the nitty-gritty.

Start your SSH tunnel

You've got access to an SSH server and you want to start using it as your proxy. To do so, you're going to set up a "tunnel" which passes web traffic from your local machine to the proxy over SSH. The command to do so is:
ssh -ND 9999 you@example.com
Of course, you're going to replace the you with your username and example.com with your server domain name or IP address. What that command does is hand off requests to localhost, port 9999, to your server at example.com to handle.
When you execute that command, UPDATE: you'll get prompted to enter your password. Once you authenticate, nothing will happen. The -N tells ssh not to open an interactive prompt, so it will just hang there, waiting. That's exactly what you want.

Set Firefox to use SOCKS proxy

Once your proxy's up and running, configure Firefox to use it. From Firefox's Tools menu, choose Options, and from the Advanced section choose the Network tab. Next to "Configure how Firefox connects to the Internet" hit the "Settings" button and enter the SOCKS information, which is the server name (localhost) and the port you used (in the example above, 9999.)

Save those settings and hit up a web page. When it loads, it's actually coming from the proxy server over an encrypted connection. You're golden!

More tips on using a secure proxy

  • To quickly start your proxy, set up a shortcut to a batch script that launches the SSH connection in a click.
  • If there are only certain (NSFW) web sites you'd like to use your proxy for, the Foxy Proxy Firefox extension lets you switch between your proxy and direction connection on a per-site basis. [via Ubuntu blog]
  • Alternately, you can set up a separate Firefox profile that uses your proxy for all web requests.
  • Set your proxy server to resolve DNS requests instead of your computer; in Firefox's about:config area, set network.proxy.socks_remote_dns = true. [via codeblog]
  • Will at Security.engine says:
    For those with slower connections, you can use the -C command line option to use SSH's compression (gzip).
This technique is as old as the hills and there are dozens of different ways and tools to get it set up. In fact, tons of Lifehacker readers have mentioned it in the comments of past posts already. What's your preferred method? Do share your proxy secrets in the comments.
------------------------------------------------------------------
设置自动重连的ssh代理

ssh -D 7070 [username]@[server]

但是ssh通道如果闲置了一段时间,就会自动断连,等我需要用到代理的时候往往又得蛋疼的重新跑一遍,非常麻烦。所以我刻苦学习前辈的经验,找到一个解决办法,在mac或linux下都可使用,分享如下:

    * 把ssh配置为免密码登录,这个一搜一大把,略过不提
    * 在/etc/inittab的最后一行加上:

      tunl:345:respawn:/usr/bin/ssh -D 7070 -qnN [username]@[server] > /dev/null 2>&1

    * 让修改的inittab马上生效

      sudo init q

    * 在/root/.ssh/config里加上几行

      Host *
        ServerAliveInterval 60

然后这个ssh通道就会自动重连了。
Update

    * 增加了一个ssh配置,要不然这个进程虽然在,但是通道已经连不上了.
from http://www.ooso.net/archives/586

--------------------------------------------------------------------
一个小服务ping出域名的真正ip以解决dns污染
来源:http://www.hawkwithwind.net/blog/2011/03/03/nslookup-%E8%A7%A3%E5%86%B3ssh%E9%9A%A7%E9%81%93%E6%97%A0%E6%B3%95%E8%AE%BF%E9%97%AEtwitter/

我最近发现,即使使用ssh 隧道,有时也会无法访问twitter, facebook等知名网站,但查询自己的ip地址已经在美国,并且另外一些被墙的网站如blogger等,却又能访问。想到应该是最近GFW的新动作造 成的。网上查了查,在google的实时搜索中发现了很多关于最近GFW升级的传闻,很多人抱怨自己ssh或者VPN开始不好用了。

只要能够连上ssh或者vpn,GFW就无法真正对我们造成威胁。仍然无法访问这些网站,极 有可能是dns污染造成的。只要能获取到正确的ip地址,就可以访问到对应的网站。然而,网上搜索到的ip地址,往往比较旧,可能已经失效。想要得到最新 最正确的dns对应ip地址,最好的方法是通过墙外的主机ping得的ip地址。将其写入自己的hosts文件就好了。

为此,我自己写了一个小小的服务,用美国主机nslookup你想问的域名,给出对应的ip。
pp.hawkwithwind.net/nslookup.php
我还提供了他的api版本,只要使用如下格式的命令,就可得到 json 格式的返回包:
pp.hawkwithwind.net/nslookup.php?server=google.com
返回形式如下
['74.125.224.176', '74.125.224.177', '74.125.224.178', '74.125.224.179', '74.125.224.180']
相信还是蛮有用的。至于原理,非常简单,用php的exec函数执行nslookup命令就可以了。
------------------

调用 autossh 或一个 expect 脚本来连接 SSH。设置选项上,相信用过 SSH 代理的同学一看就知道怎么设置了,需要说明的就两点,“为其他电脑提供代理”,选中后,如果你的局域网中有其他电脑或设备,只需将代理设置为本台电脑的 IP 和相应端口,就可以使用 SimpleSSHProxy 提供的代理了。“使用密码”选项,我已经提到过了,autossh 对使用密码的 SSH 认证无法很好的支持,但是 autossh 的连接管理特性又十分方便,所以,如果你使用的是 SSH 密钥验证方式,就不用选择“使用密码”,软件就会调用 autossh。如果你不得不使用密码验证,软件会调用一个 expect 脚本来连接 SSH,同样可以提供类似 autossh 的断线重连等功能。当然还是推荐大家设置 SSH 的密钥认证,具体设置方法请自行搜索。如果你实在懒得设置密钥或者服务器比较特殊,只支持密码验证,那就没的选了。
-------------------------------

各平台创建 SSH Tunnel 的免费客户端


SSH 的用处有很多,比如远程服务器管理,博客搬家,创造安全的上网环境等。当然,很多人不愿意去记复杂的命令,在终端中逐一输入。因此,本文主要推荐几款各主 流平台上用来做 SSH Tunnel 的免费客户端。文中软件并没有很详细的使用说明,只作为一般性介绍,如有不明请搜索之,或参考文后的 “推荐阅读” 部分。请注意和谐使用,也不要浪费资源。注意,此处仅仅讨论的是用来做 SSH Tunnel,所以部分软件并不能实现诸如 Putty 等 SSH 客户端软件所提供的功能。

SSH via 维基百科

SSH为Secure Shell的缩写,由IETF的网络工作小组(Network Working Group)所制定;SSH为建立在应用层和传输层基础上的安全协议。
传统的网络服务程序,如FTP、POP和Telnet其本质上都是不安全的;因为它们在网络上用明文传送数据、用户帐号和用户口令,很容易受到中间 人(man-in-the-middle)攻击方式的攻击。就是存在另一个人或者一台机器冒充真正的服务器接收用户传给服务器的数据,然后再冒充用户把数 据传给真正的服务器。
而SSH是目前较可靠,专为远程登录会话和其他网络服务提供安全性的协议。利用SSH协议可以有效防止远程管理过程中的信息泄露问题。透过SSH可以对所有传输的数据进行加密,也能够防止DNS欺骗和IP欺骗。
SSH之另一项优点为其传输的数据是经过压缩的,所以可以加快传输的速度。SSH有很多功能,它既可以代替Telnet,又可以为FTP、POP、甚至为PPP提供一个安全的“通道”。

MAC 平台 


SSH Tunnel Manager(只推荐此款ssh client! mac下的其他ssh client都是垃圾,都用不了。)

软件名称SSH Tunnel Manager
授权 / 价格开源软件 / 免费
系统平台Mac OS X
运行环境所有
网址官方网站

另外一款可以保存多账户的客户端,支持 Socks4/socks5.
SSH Tunnel Manager


Linux平台

(1). Gnome SSH Tunnel Manager

软件名称Gnome SSH Tunnel Manager
授权 / 价格开源软件 / 免费
系统平台Linux
运行环境Gnome
网址官方网站

gSTM 是一款运行于 Gnome 上的用于 SSH Tunnel 的开源客户端,对于多账户管理比较方便。注:其配置文件是以 XML 格式保存。
具体使用可以参照 “Manage SSH Tunnels with Gnome SSH Tunnel Manager @ Ubuntu Geek
Gnome SSH Tunnel Manager

(2). SSH Tunnel Manager

软件名称SSH Tunnel Manager
授权 / 价格开源软件(GPLv2) / 免费
系统平台Linux
运行环境PyGtk
网址官方网站

一款使用 Python 开发的客户端。据作者所说,由于 Ubuntu 自带的客户端不能满足其要求,也作为学习 PyGtk 开发的实践,因此有了本软件。如果,你也是正在学习 PyGtk 或者对 Ubuntu 自带的客户端不满意,不妨试试,具体功能说明请参考官网。
SSH Tunnel Manager

(3). Terminal

使用终端命令,应该是最符合 Linux 大部分用户习惯的方式了: ssh -qTfnN -D 7070 remotehost
以下为参数说明:
All the added options are for a ssh session that’s used for tunneling.
-q :- be very quite, we are acting only as a tunnel.
-T :- Do not allocate a pseudo tty, we are only acting a tunnel.
-f :- move the ssh process to background, as we don’t want to interact with this ssh session directly.
-N :- Do not execute remote command.
-n :- redirect standard input to /dev/null.
In addition on a slow line you can gain performance by enabling compression with the -C option.

iOS平台 

1. iSSH (App Store)

iSSH 与 Mac 上的 iSSH 并不是一个公司的产品。而且此 iSSH 并不免费,售价为 9.99 美元。目前 iSSH 只能用来进行远程连接,并不能进行端口重定向。

2. MobileTerminal (Google Code)

需要 iPhone/iPod touch 已经 jailbreak 过,并安装了 OpenSSH。打开 MobileTerminal 输入:ssh -D 7070 username@host,然后输入密码即可。想要关闭,可以在终端输入 killall ssh,如果仍处于 SSH 登录状态,可以直接输入 logout。

3. 替代Mobile Terminal的免费SSH应用软件:zaTelnet
在4.xx固件以前,最好的免费SSH软件就是Cydia里的Mobile Terminal,可惜4.xx固件以后因为Mobile Terminal和固件不兼容,新版的Mobile Terminal感觉又不好用,Nie把目光投向App Store里的免费SSH应用,因为App Store里的软件将来不会出现兼容性问题,个人也更倾向于安装ipa的软件。在App Store里免费的SSH软件还真少,Nie只找到zaTelnet可以使用SSH。
可能有的同学不知道怎么设置zaTelnet来执行本地命令,也就是怎么代替Mobile Terminal的功能,具体设置参考Nie的配置。
zaTelnet配置
"Name"处可以随便填;"Network"里是关键,"URL/IP"一定要填"127.0.0.1","Port"处填"22";"Type"里选第一个选项就行;"Login"里的"User name"填"root","Password"填"alpine",如果你修改过SSH密码就填你修改过的密码。
试用了一下,完全可以替代Mobile Terminal,Mobile Terminal做得到的zaTelnet也完全没有问题,除了不能滚动屏幕,甚至比Mobile Terminal还好用,你也赶紧试试吧。 

4. 一款代替Terminal的免费软件:Rove Mobile Admin
发现还有Rove Mobile Admin,比昨天找的zaTelnet还要强一些,至少可以滚动屏幕,能设置的参数也更多。这软件应该是主要为Mobile Admin Server而写,顺便带免费的SSH、Telnet和RDP,昨天Nie看这名字和SSH没有多大关系就没有下下来试用,才错过了,还好今天又去多看了几眼。软件具体设置参考下图。
Mobile Admin设置
“Password”处要注意,如果没有修改过iPhone默认SSH密码,就填“alpine”,修改了就填修改过的密码。“Columns”和“Rows”都是自定义参数,“Columns”表示横排显示多少个字符,iPhone在竖屏情况下,38刚好,横屏的话57刚好;“Rows”表示光标和iPhone虚拟键盘的距离,设置13行刚好,14也可以。
该应用也可以后台运行,所以Rove Mobile Admin也是一件用SSH~穿~墙的好工具。 

Android平台【2010-11-29 新增】


目前在 Android 上 SSH Tunnel 的应用还不明朗,虽然已经有人将 TTP/HTTPS 重定向到 SSH Tunnel,但似乎还有一些问题。本人没有 Android 手机,因此无条件验证,有兴趣的用户可以参考以下内容:

1. ConnectBot (Google Code)

ConnectBot 是 Android 平台上一款开源 SSH 客户端软件。

2. SSH Tunneling On Android via Shantanu’s Technophilic Musings

3. SSH Tunnel for Android System【2011-07-27 新增】

一款国人基于 ConnectBot 开发而来的 SSH tunnel 工具。感谢 USAssh代理 在评论中推荐。应用文章看这里

推荐阅读 

----------------------------

利用Putty通过ssh端口转发实现代理访问

浏览器先通过加密通道链接到一台服务器上,然后通过这个服务器再访问整个互联网。主要的用途就是这个绕道访问。具体你需要通过加密通道绕过谁? 谁用谁知道……

具体配置过程:
在SSH登录工具Putty的登录设置中配置tunnel,目标设置为Dynamic,添加一个端口7070,再按Add,一个动态转发端口就实现了;

然后用相应帐号ssh登录后:除了登录的终端窗口意外,本地的7070连服务器的22端口之间就有了一个SSH加密的转发通道了。

为了方便切换,可以使用FireFox的SwitchProxy tool插件,设置socks代理通过本地的127.0.0.1:7070 进行传输。


MSN的机制类似:就是在连接配置中设置sock5 加密代理。

附:
获得国外的SSH帐号或者有Dreamhost虚拟主机的可以增加ssh用户:都可以用类似机制进行加密访问。

(感谢number5:

更简单方便的setup方式是使用 putty的后台命令行程序plink:

plink.exe -N 
-D 127.0.0.1:7070 username@ssh-server.com -pw password -P ssh-server-port 
也可写成:
plink.exe -N -D 127.0.0.1:7070 -l username ssh-server.com -pw password -P ssh-server-port 
其中 -N 表示不需要shell,
username@remote.ssh.server 换成你ssh帐户名和主机名或者ip地址
,password换成你ssh帐号的密码,(如果ssh主机端口为22,则-P 22也可不写出来。注意这里的P是大写,不能用小写
我加了 -N,用不了。因此我的命令为:plink.exe -D 7070 username@ssh-server.com -pw password或者用putty.exe也可:putty.exe -D 7070 username@ssh-server.com -pw password
用dreamhost上的帐号试了一下,真的很快).

如何在Windows下使用密钥方式登录Linux服务器:
如果设置需要基于密钥的登录(如果不设置密钥密码,就可以自动登录了),
我没有试成使用puttygen生成的密钥(公钥/私钥)直接部署在Linux服务器上。目前成功的方法是:先在服务器上用服务器上用./ssh-keygen生成密钥对,将公钥 id_rsa.pub >> 部署到要登录到的服务器上:/home/username/.ssh/authorized_keys 中,密钥在Windows客户端下使用:将密钥 id_rsa下载到本地,然后用puttygen导入id_rsa 另存转换为putty格式的密钥id_rsa.ppk即可。然后使用 plink -i c:\path\to\id_rsa.ppk username@example.com方式登录。
一般SSH服务器都支持公钥验证,用puttygen生成一个key-pair,就可以实现后台自动登陆SSH服务器。

from: http://www.chedong.com/blog/archives/001246.html  
http://thinkhole.org/wp/2006/05/10/howto-secure-firefox-and-im-with-putty/ (被封,需翻墙)
------------

用putty.exe登陆ssh server的步骤:
首先运行putty.exe,然后在窗口右上部host name处,输入你的webserver的主机名或ip地址,然后点击左侧的SSH,再点击其下展开的菜单中的tunnels,然后选择窗口右下部的dynamic,然后在其上面source port处,输入7070,然后点击右边的“add"按钮,然后点击窗口下部的open按钮,就会弹出putty的命令行窗口,然后在login as后面输入ssh账号的用户名,回车,输入ssh账号的密码(输入密码时,界面不会有任何显示),回车,即可登录ssh server.
-----------------------------------------------------------------------------------------
If you use PuTTY from the command line, here is a faster way to establish the secure tunnel:

putty.exe -D 9853 username@sshhost.com and press Enter

Just replace username with your actual username and ssh.host with the address of the SSH server. When it logs in you will automatically be asked for your password. Once that is accepted the encrypted tunnel is automatically created on port 9853 on your computer.

Another neat trick for command line users: Rename PuTTY.exe to ssh.exe. Move the newly renamed file to c:\windows\. From then on, all you have to do to establish the tunnel from Windows is click 'Start --> Run...' to open the 'Run' dialogue box and then type ssh -D 9853 username@sshhost and press Enter. Replace username with your real username and sshhost.com with the address of ur SSH host.
----------------------------------------------------------------------------------------------
MyEnTunnel/PuTTY/Plink速度之所以慢是因为plink的问 题,MyEnTunnel/PuTTY都是plink的前端。调用的都是 plink,plink的beta版是有问题的它的速度不会高于40KB/s的。无论你的ssh服务器速度多快,这个问题在plink的dev版中得到了 解决,也就是说使用dev版的plink时就不会有速度慢的情况了。
这大概也是有的人改用Tunnelier后速度没有变化的原因了,大家可以测试下使用 plink的beta版http://putty.very.rulez.org/latest/x86/plink.exe和使用dev版http://tartarus.org/~simon/putty-snapshots/x86/plink.exe速度的差别。
现在就到http://ssh.daili.vc取得免费的ssh账号后测试吧。测试后你就会发现使用plink的dev版速度和使用Tunnelier是一样的明显高于plink的beta版!
呵呵,这样你就不要忍受体积庞大的Tunnelier了,可以继续使用简单方便的MyEnTunnel了,你只需要把你的plink改为dev版,快点下载http://tartarus.org/~simon/putty-snapshots/x86/plink.exe替换吧!
--------------------------------------------------------------------
在MyEnTunnel中创建多个SSH账户
不知有没人遇到跟我相同的情况,MyEnTunnel 3.5.2右键点击托盘图标,“账户”(profiles)一项是灰色的,不可选的,而在软件主界面中也没有任何创建新“账户”的选项。但3.4.1似乎就没有这个问题。如果你只有一个SSH账户,或你用的已经是3.4.1稳定版,请忽略本文。

解决方法如下:
Win+R,输入MyEnTunnel完整路径,空一格再加个新配置,如:
D:\MyEnTunnel\myentunnel.exe MediaTemple
(当然你也可以通过建立快捷方式并编辑之来达到相同目的,不赘述了。)
编辑完SSH账户信息并保存后,程序目录会多出来3个配置文件。这时退出并再次运行 MyEnTunnel,“配置”一项即变为可选,也可以直接创建新账户了。(其实你没必要这么费劲只需在按住Ctrl键鼠标点击并拖动 “myentunnel.ini”配置文件新建一个“复件myentunnel.ini”再打开myentunnel软件就会发现“配置”一项即变为可选 了)
再给个tips:MyEnTunnel的作者在主页上说了,使用dev build的plink.exe会快很多。我换了看youtube速度果然是质的飞跃。PuTTY 官网就能下载到,自己仔细找找。
多配置的使用dev build的plink.exe的中文完美的MyEnTunnel下载地址:http://sharesend.com/2laka
http://nemesis2.qx.net/rdownload.php?filename=setup_myentunnel.exe (这是Stable Release 3.4.2.1版,右键点击托盘图标,“账户”(profiles)一项是可用的。建议用此版本。
-----------------------------------------------------------------------------------------
putty中,产生私钥的方法:
1、通过putty.exe用自己的用户名登陆到linux服务器,然后:
ssh-keygen -t rsa
一路回车确认,生成的公/私钥文件缺省在 ~/.ssh/ 下
进入.ssh目录
mv id_rsa.pub authorized_keys // (更改为系统默认的公钥文件名)
将id_rsa文件(私钥)传到windows机器下,将原来的id_rsa文件删除

2、用PUTTYGEN.EXE转换id_rsa文件为putty的格式(TortoisePlink.exe可以使用):
菜单:Conversions\ImportKey ,选中id_rsa文件
直接点"Save private key"按钮将新格式的文件保存到硬盘,如D:\mykey.ppk

3、设置putty.exe自动登陆:
\Connection\Data:Auto-login usename
\Connection\SSH\Auth:Private key file for authentication 选择上面生成的密钥文件

4、更改登陆的字体:
Window\Appearance:Font settings Change...

5、显示UTF-8的终端中文字符:
Window\Translation:Character data assumed to be in which character set选择UTF-8或需要的编码
http://www.fwolf.com/blog/post/279 配置ssh的自动登录
--------------------------------------------------------------
A 'shell' is how you interact with the 'kernel'. The kernel is the
software that translates your commands into instructions that the
hardware (machine) can understand. The origin of the word 'shell'
actually comes from MULTICS, which UNIX attempts to mimic.

/bin/sh Stephen Bourne's Shell
/bin/csh A shell with a C-like syntax
/bin/ksh David Korn's Shell (default)
/usr/pkg/bin/bash GNU's Broken Again SHell
/usr/pkg/bin/tcsh BBN TENEX Shell .. Not quite like EXEC
/usr/pkg/bin/rc PLAN 9 'Run Commands' Shell
/usr/pkg/bin/zsh Paul Falstad's Shell

The best thing to do is read up on the shell using the 'man'
command. You can run the shell by just executing it. When
you are sure you really want to change to that shell you:

TELNET to 'ol.freeshell.org' to run password/shell maintenance.

Note, you can ssh into 'tty.freeshell.org' to encrypt your
session before your telnet to 'ol.freeshell.org'
---------------------------------------------------
http://docs.google.com/View?docid=ajbgz6fp3pjh_2dwwwwt&revision=_latest  PuTTY 中文教程
http://chaifeng.com/blog/2007/06/putty_200611.html
------------------
2. Port Forwarding  http://alumni.ox.compsoc.net/~steve/portforwarding.html 该文中有个很好的例子,展示了路由在做portforwarding事修改数据报的表头中的目的/源的地址和port。
3. Port Forwarding How To  http://www.home-network-help.com/port-forwarding.html 该文有三个小例说明如何设置路由让内部网的三台机子分别能对外网提供Web服务,Remote Destop连接和游戏服务器。
4. HOWTO: SSH Tunneling Made Easy  http://www.revsys.com/writings/quicktips/ssh-tunnel.html
5. Using ssh Port Forwarding to Print at Remote Locations http://www.linuxjournal.com/article/5462
--------------------------------------------------------------------------------------------------------
现在几乎就生活在ssh之中了。因为无论生活还是工作都离不开它,真是由衷的感谢那些设计和开发出这个伟大工具的程序员们。ssh最主要的功能就是把所有传输的数据加密,最初是的设计是为了替代传统明文传输的telnet、rlogin等程序,以避免密码嗅探攻击。而且ssh传输的数据还是经过压缩的,所以还能加快传输速度。
ssh是Secure Shell的简写,也就是说它能提供给你一个安全的shell,而保护这个安全shell的加密通道是通过端口转发(Port Forwarding)来完成的。这意味着ssh可以帮你把任意原本不安全的端口连接起来,提供给你安全的通道。安全的端口转发,这一点可以让ssh来完 成很多有趣的应用。

SSH隧道代理

近期一个常见应用就是通过ssh本地端口转发数据包到国外主机,以穿透GFW访问被墙的网站。应用场景是这样的:
  • 你的国内主机,比如一台笔记本
  • 你拥有ssh权限的国外主机: forward.com,用户名是 user
  • 被墙的网站,比如Google主机: google.com
在笔记本上运行:
ssh -L localhost:1080:google.com:80 user@forward.com
这种方式称作本地转发(Local Forwarding),意思就是把本地端口1080通过foward.com转发到了Google服务器的80端口上,这样你访问本地的1080端口就和访问Google服务器一样了。
不过这只是在传输层的端口转发,因为被GFW的网站很多,所以一个个的转发未免太麻烦了。所幸ssh还提供应用层的端口转发(a local “dynamic” application-level port forwarding),这时候ssh就扮演一个sock代理服务器角色,目前支持sock4和sock5。下边就是我们平时常用的ssh tunnel的建立办法:
ssh -D 1080 user@forward.com
这样就在你的本地架设了一个sock proxy,然后你可以通过这个proxy来访问被墙的网站了,如果不希望打开一个shell,可以加上参数-N
如果你穿透NAT,有些防火墙看你半天不活动,会终止你的连接。不过你可以配置你的ssh客户端,让它定时在应用层发送一个keepalive的请求,这样能够保持你的sock proxy连接。比如每隔120秒发送一次,则在 ~/.ssh/config 中写入:
Host forward.com
    ServerAliveInterval 120
如果你使用Firefox,推荐安装FoxyProxy插件,可以根据规则匹配被墙的网站地址。如果使用Chrome,可以使用Switchy插件。这样没有被墙的网站,你还是可以直接连接。这也是我觉得ssh tunnel比VPN更好用的地方。
如果你使用Windows主机,那就没有OpenSSH工具包,你需要去Putty网站下载一个plink,把它放到你的PATH目录,比如C:\Windows\System32,然后在命令行中运行:
plink.exe -D 1080 user@foward.com
如果你讨厌Windows那个黑乎乎的cmd窗口,那么你可以另起一个进程,把这个proxy放在后台运行,写一段VB脚本,如果连接失败,plink进程会自行结束:
set ws=WScript.CreateObject("WScript.Shell") 
ws.Run "plink.exe -N -D localhost:1080 -pw password user@forward.com",0

SSH反向穿透

ssh既然可以把本地端口转发到远程端口,同样也可以把远程端口转发到本地端口(Remote Forwarding)。比如大家平时工作的时候都是在公司的NAT里,也许你是个勤劳的员工,回家之后还想在公司主机上干点活,一般公司都给大家配备一 个VPN帐号,可以让你连接公司主机。但是,如果你有一台外网主机,你依然可以通过ssh端口转发来方向穿透防火墙,访问公司主机。应用场景如下:
  • 你的公司主机:desktop
  • 你可以访问的外网主机:myhost
  • 你在家使用的笔记本: notebook
首先你需要从公司主机发起一个ssh连接:
ssh -R localhost:9922:localhost:22 myhost
这里我写了两个localhost,其实是想加深大家对端口转发的理解,因为为了安全起见,侦听端口默认都是绑定在loopback上的,所以如果 只是本地访问,第一个localhost总是可以省略的。这里说明一下,第一个localhost代表的是myhost的loopback地址,第二个 localhost代表的是desktop的主机地址。
所以你下班回家,只要登录到myhost上,访问9922端口,就和访问desktop的22端口的效果是一样的。
from: http://blog.erera.net/ssh.html
------------------------------------------
如何在各种操作系统下设置ssh tunnel

Linux/Unix Generic

Easy
  1. Open a terminal
  2. Use your webhosting account, or external server that has SSH (secure shell) capability. You need to have a username, password and hostname for your account for the following steps.Here is a quick example:
    ssh -D 1080 username@hostname.com
    Here is the variant I use which adds compression, and not logging into your server (aka, only forwarding ports). The command also prints out information about what is connecting. I love to see the output that shows all this working which the -vv option provides:
    ssh -vv -CND 1080 username@hostname.com
  3. Then enter your password when prompted.
  4. Install Mozilla Firefox on your system.
  5. Install the add-on, FoxyProxy.
  6. Follow the instructions for setting up FoxyProxy here: http://foxyproxy.mozdev.org/configuring.html or with pictures, but blocked by the GFW. The crucial step is to add the hostname as localhost and the port as 1080 in the Manual Proxy Configuration. Also, make sure to select SOCKS 5 proxy. I also add to foxyproxy’s global settings to “Use SOCKS proxy for DNS looksups.” The GFW is notorious for poisoning DNS lookups (aka, your looking for domain names that match IP numbers). Egad! Oh, make sure to name your proxy something like localhost SLST or localhost SSH + Socks Tunnel.
  7. To route all your web browsing traffic to your SLST, then you can select the mode in foxyproxy to use your proxy for all urls.
  8. More advanced is to “Use proxies based on their pre-defined patterns and priorities”. Here is an example of the lines needed for facebook, youtube, and twitter. For each URL Pattern, make sure the pattern is enabled, name it what you want, then add the below pattern after the colon to the :URL pattern:” field. Make sure the Whitelist and Wildcards radio buttons are selected.
    URL Pattern: *.youtube.com/*
    
    URL Pattern: *.facebook.com/*
    
    URL Pattern: *.twitter.com/*
    
  9. Add more patterns to sites you find blocked. Its pretty simple to copy the handiwork above for any other sites you find blocked.
  10. Save your patterns and foxyproxy, and try to visit youtube, facebook, twitter, and other patterns you setup.
  11. If this doesn’t work, file some comments here or on the my wiki page. This isn’t a super simple setup for some and I might have made mistakes in my brain dump. The key pieces will fail if you don’t have SSH access, or if you don’t setup your foxyproxy correctly.
Advanced
The setup I run involves the above easy setup, but I used the following autossh-based script I titled, local_ssh_tunnel. I used autossh because it keeps the ssh connection alive through closing/suspending my laptop, dodgy wireless reception and other general bugs that harm one’s net connection.
  1. In Ubuntu (or other distro), install autossh through synaptic or your favorite package manager. In Gentoo, emerge autossh should do the trick.
  2. Open a file such as /home/USERNAME/bin/local_ssh_tunnel
    #!/bin/bash
    
    #
    # local_ssh_tunnel
    #
    # use proxy to connect to localhost no port 1080
    #
    
    SERVER=USERNAME@HOSTNAME
    
    # 1080 is standard port
    PORT=1080
    
    if [ "$1" != "" ]
    then :
        SERVER="$1"
    fi
    
    AUTOSSH_GATETIME=0 AUTOSSH_PORT=20000 AUTOSSH_DEBUG=1 \
    autossh -v -CND 1080 $SERVER
    
  3. Save the script.
  4. Run the following command:
    chmod 700 /home/USERNAME/bin/local_ssh_tunnel
  5. I then set the above script to run as a startup application inside of gnome in a terminal. In Ubuntu you can set this by doing the following steps.
  6. Navigating to upper left-corner Application Icon > System > Preferences > Startup Applications
  7. Clicking Add
  8. Then filling out the fields:
    Name: BACKGROUND SLST (Second Line SSH/Socks Tunnel)
    Command: xterm -e /home/USERNAME/bin/local_ssh_tunnel
    Comment: Runs SLST in the background in terminal window
    
  9. Click Save
  10. Close the startup
  11. If you want this immediately, you can run /home/rejon/bin/local_ssh_tunnel inside of a terminal window.
  12. Now, you can just leave the above open in the window and AUTOSSH will make sure to keep your ssh connection alive.
  13. Then start on step 4 above in the Linux/Unix Generic section.

Windows

There is already a great guide for setting this all up in windows. I used it yesterday. Just remember to replace the HOSTNAME with your host and to use the port of your choosing. I use 1080 because its the standard port for this operation and generally not restricted for this activity on most systems.
Here is another guide, which is even better, but has pictures. I will merge my steps with this guide now:
  1. Follow steps at for graphically setting up SLST until the setting up Firefox section, making sure to replace HOSTNAME, USERNAME and the port for the one of your choice.
  2. Then start on step 4 above in the Linux/Unix Generic easy section for setting up Firefox with the correct settings.
ASIDE: Here is also another guide, which is helpful explaining the basic concepts in one page, but blocked by the GFW.

Mac OS X

Easy
Since Mac OS X is a Unix-based variant you can do the easy steps above. The crucial difference is that many don’t know where one might find Mac’s terminal in step 1.
  1. Navigate to a finder window
  2. Then navigate to the Utilities folder
  3. Double-click the terminal to be able to enter commands
  4. Continue with step 2 in the easy steps above
Advanced
Setup a SLST setup not on the command line, but using the SSH Tunnel Manager graphical application. I cannot find a graphical guide to doing this. One of the great things about using AUTOSSH in the Linux/Unix/Generic advanced guide is that it keeps the connection alive through suspend, or internet outtages. There should be an option to keep-alive the connection in the SSH Tunnel Manager. Regardless, please visit the Wiki page for this article to add any notes here about graphical setup for Mac OS X to accomlish the tasks I setup here.

Conclusion

The crucial steps that I’m not really including is that you need to have some SSH capable server outside of the jurisdiction that is irregularly filtering the Internet. If you have a linodeslicehostmediatemple, or dreamhost hosting account (which is also my ranking of best hosts in order) for your website, put that extra bandwidth to good use! That is what I helped Matt do so he can use his matthope.org external server as an external lifeline outside of here! You should do the same!
And, note this is much better than an unsecure proxy, using some shifty free proxy server that might go offline at anytime, faster than using Tor, and gives one the flexibility to surf raw and, or, secure.
Many have blogged about this type of setup. I wanted to spread the news to all the people I know, hopefully get someone to translate this into Chinese, and generally get this out of my mind so the next time I’m asked how to get onto to Facebook or through the GFW, I can point someone here, or you can pay me to set it up. #haole! Oh, and this guide is useful everywhere in the world, in Iran, North Korea or even the United States
from: http://rejon.org/2009/07/access-facebook-through-the-great-firewall-second-line-ssh-tunnel/
http://rejon.org/wiki/IDEA_20090715_Second_Line_SSH_Tunnel
相关文章:
OpenVPN setup HowTo: allow an external laptop to connect to your home network
l
Who knew you could create your own free web proxy server with Google AppEngine?
Proxy preventing lost internet connection?
How to make Iceweasel identify itself as Firefox using the User agent switcher extension
Bypass almost any firewall with an SSH tunnel on port 443
Configure SSH tunneling with Ubuntu and surf Priva
---------------------------

Proxy using ssh tunnel under linux

A simple example

Let’s start with a simple example. We can access a sshd server sshd_server and we want to use it as a socks5 proxy server. It is simple by using ssh:
ssh -D 1080 username@ssh-server
After that, set the browser such as firefox’s proxy option to use socks5 proxy 127.0.0.1:1080. That’s it!

Making ssh proxy

We can set up a more complex proxy server through ssh. For example, we have a sshd server s2 and another server s1 as the proxy server. Then we can set up a proxy server system using ssh tunnel. s1 will act as the proxy server, while s2 connects to the service provider (s3). The overall system can be shown as this:
c0:p0 <--> s1:p1 <==> s2:p2 <--> s3
Maybe most of the time c0 and s1 are the same machines as the simple example at the beginning of the post.
Using ssh as a proxy to browse the web is very useful under some situation: Local access restriction such as behind a strict firewall in some country, company or school; You are in a insecure network environment while you want to login to your account.
Now let’s look at how to set up proxy by using ssh tunnel. This uses ssh’s “dynamic” port forwarding function by using parameter “-D”. ssh allocates a socket to listen to port on the local side, optionally bound to the specified ip address. Whenever a connection is made to this port, the connection is forwarded over the ssh channel, and the application protocol is then used to determine where to connect to from the remote machine.

1) Proxy listening to localhost port only

This proxy server can only be used on localhost, which means the other users can not use it. c0 and s1 in the graph above are the same machine.
The command is:
ssh -D p1 username@sshd_server
p1 is the port on localhost. Any port larger than 1024 can be chosen as p1. After setting up this proxy tunnel, set the proxy option in browser to 127.0.0.1:p1 and using socks5. Then it is done. Enjoy it now :) .

2) Proxy listening to specific IP

This kind of proxy server can provide service to other users. Users (and include yourself of course) can use this socks5 proxy with address s1_ip and port p1.
The command is:
ssh -D:s1_ip:p1 username@sshd_server
This command sets up a socks5 proxy server on s1. The proxy address is: s1_ip:p1.
* Some useful ssh arguments
There are some other ssh arguments that can make the port forwarding more convenient for us:
-N  Do not execute a remote command. This is useful for just forwarding ports.
-f  Requests ssh to go to background just before command execution.
-n  Redirects stdin from /dev/null (actually, prevents reading from stdin).
-q  Quiet mode. Causes most warning and diagnostic messages to be suppressed.
These arguments can be used with -D for different usages. I like to use this combination:
ssh -nfND 8080 username@sshd_server
When I want to close the ssh proxy tunnel, I need to find the pid of it by
ps aux | grep ssh
and then kill it.

Port forwarding squid proxy

This post mainly focus on using ssh to build up the proxy system. But the connection between the client and the other kind of proxy server such as squid can also make use of ssh tunnel. I only provides a simple example here, while more details of ssh port forwarding can be found from port-forwarding-using-ssh-tunnel. For example, the proxy server and port is proxy:port. Now we can port forwards port 8080 on localhost to it by this:
ssh -L 8080:proxy:port username@sshd_server

from http://pkill.info/blog/post/proxy-using-ssh-tunnel.html
------------------------------------------------------------------

Port forwarding using ssh tunnel under linux

 

A simple example

Let’s start with a simple and useful example: we want to forward local port 8080 to server:port. We can easily do this by using ssh like this:
ssh -L 8080:server:port username@ssh_server
ssh_server is the sshd server that we can use. Then connection to 127.0.0.1:8080 will be automatically forwarded to server:port.

Port forwarding

Port forwarding (or tunnelling) is a method to forward one network traffic to another. For example, there are three servers s1, s2, s3 and one client c0. There is a ssh tunnel between s1 and s2. When c0 sends a packet to s1′s port p1, the packet can be forwarded through the traffic through the tunnel between s1 and s2 and will arrives s3′s port p3. The packet of the opposite direction follows the opposite way. That is:
c0:p0 <--> s1:p1~s1:p1' <==> s2:p2~s2:p2' <--> s3:p3
From c0′s view, it connect to s1′s port p1, but actually, the service is provided through s3′s port p3. If c0 is the user or the client of the service, then the ssh security tunnel will exist between s1 and s2. This will be very useful. For example, we can use this method to secure the insecure network such as SMTP, HTTP, POP3, etc. If c0 and s1 are in the secure local network area and s2 and s3 are in another secure local network area, while the two local network area are connected through the insecure internet. The connection between the client c0 and the application sever s3 is insecure. Then we can create the ssh tunnel between s1 and s2. The tunnel is encrypted and secure. So s3′s service can be provided to client c0 in a secure way as the traffic in the insecure network is encrypted. This is a method to secure an “insecure” connection, of course, with the cost of encryption and decryption.
We do not need to have exactly four server/clients. c0 and s1 can be the same server and c0 can just connect to the localhost which is itself. It the same for s2 and s3. So there may be two, three or four server/clients in this system. Only one server will also work, but it’s actually useless. An usual way of using this is that c0 and s1 is the same server. After the tunnel has been set up, c0 will use the forwarding port on localhost itself .
Either s1 or s2 can be the sshd server for the ssh tunnel. So there are two kinds of port forwarding: Local forwarding and Remote forwarding.

Local forwarding

Another name of local forwarding is outgoing tunnel. s2 is the sshd server of this ssh tunnel, while s1 is the ssh client. From the view of s1, the tunnel is outgong and it is listening on the local port. So it is called “local” forwarding or “outgoing” tunnel.
We also use the previous example that we want to port forwards port p1 of s1 to port p3 of s3. The method is using this command on s1:
ssh -L p1:s3:p3 username@s2
sshd usually listens on port 22 which is p2 here. If sshd’s service port is not the normal one 22, then add the -p p2 argument to ssh. When a packet is received on port p1 by s1, s1 sends this packet through the tunnel between s2 and itself, then s2 will send this packet to s3:p3.

Remote forwarding

Or incoming tunnel. In this case, s1 is the sshd server and s2 is the ssh client. From the ssh client s2′s view, the remote side (s1) listens on the port and forwarding packet through the tunnel. The ssh client gets incoming packet through the tunnel.
The method is using this command on s2:
ssh -R p1:s3:p3 username@s1
The packet to s1:p1 will be forwarded to s3:p3 through the tunnel as the local forwarding. This is useful especially when s1 and s3 are behind a firewall that does not allow opening any port. This method provides a way to remote control a machine behind the firewall. We can also see that even with a strict firewall, the protected local area network can also be controlled remotely.
ssh is a user space application, and the performance of port forwarding is not as good as some other approach such as iptables. But ssh tunnel is easy to set up even without root privilege granted to the user, which make it a very convenient tool on Linux/Unix systems.

sshd configuration

GatewayPorts should be “yes” in /etc/ssh/sshd_config on sshd server if remote forwarding is enabled for machine c0.
GatewayPorts:
Specifies whether remote hosts are allowed to connect to ports forwarded for the client. By default, sshd binds remote port
forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be
used to specify that sshd should allow remote port forwardings to bind to non-loopback addresses, thus allowing other hosts to con-
nect. The argument may be “no to force remote port forwardings to be available to the local host only, “yes to force
remote port forwardings to bind to the wildcard address, or “clientspecified to allow the client to select the address to
which the forwarding is bound. The default is “no”.

from http://pkill.info/blog/post/port-forwarding-using-ssh-tunnel.html
---------------------------------------------------------------------------

在linux下,建立 SSH Tunneling Proxy的方法

在使用客户端连接 SSH Tunneling Proxy 之前,我们必需先通过相应的工具建立 SSH 隧道,常用的工具有原生的 SSH 命令、 AutoSSH 及 Plink 等。

原生 SSH

在终端下输入如下命令
ssh -N -v username@hostip -D 127.0.0.1:7070
把其中的 username , hostip 替换成你自已的内容。
第一次运行此命令需要输入 yes 来接受证书,最后输入 SSH 密码。如果你不想每次都输入密码的话,可以采用证书认证方式。
终端下运行 ssh-keygen 命令来生成证书,直接按三次回车无需输入任何内容。
ssh-keygen
进入 SSH 目录
cd ~/.ssh
打开 id_rsa.pub 文件,复制里面的所有内容。
然后通过 ssh 连接到远程 ssh 主机,进入 ~/.ssh 目录,打开 authoried_keys 文件,把刚才复制于 id_rsa.pub 的内容粘贴进去。
这样下次再建议 ssh tunneling 的时候就无需输入密码了。
最后你可以建立一个 shell 脚本文件,这样不必每次输入命令了,方便使用。

AutoSSH

AutoSSH 的使用方法和 SSH 类似,只是它提供了断线自动连接功能,这样就不必每次重新输入命令了。
安装
sudo apt-get install autossh
使用
autossh -M 2000 -N -v  username@hostip -D 127.0.0.1:7070

Plink

Plink 最大的好处在于可以指定密码,不必采用证书方式就可以不输入密码建立链接了。
安装
sudo apt-get install putty-tools
使用
plink -N -v username@hostip -D 127.0.0.1:7070 -pw password
把其中的 username , hostip , password 替换成你自已的内容。

gSTM

gSTM 是图形化工具,见此文:gSTM:Ubuntu 上的 SSH Tunneling 图形界面管理工具

介绍

之前我们在 Ubuntu 下如何使用 SSH Tunneling Proxy ? 一文中介绍了如何在 Ubuntu 下使用 SSH Tunnel 这一神器,此文中基本上介绍的都是基于命令行的工具,可能对新手来说比较难理解。而现在有个名为 gSTM 的软件则提供了图形界面,它全称为 Gnome SSH Tunnel Manager ,是一个 Linux 上用来管理 SSH Tunnel 的图形管理工具,方便用户建立多个 SSHTunnel 隧道。
主页: http://sourceforge.net/projects/gstm/

安装和使用

Ubuntu 下安装
sudo apt-get install gstm
打开 gSTM,按下图进行配置,把相应的内容替换成你自已的数据。

最后到主界面进行 Start 的就 OK 了。

客户端配置介绍

FireFox + AutoProxy

下载安装 AutoProxy 插件,地址: https://addons.mozilla.org/zh-CN/firefox/addon/11009 。
使用 AutoProxy 的好处在于,只有访问被墙网站的情况下 FireFox 才通过 SSH Tunneling Proxy 访问网站,所以对于国内网站还是采用本地线路。
安装完插件后,只要默认启用 SSH -D 代理可以了,Autoproxy 的默认端口配置就是 7070 ,如果你之前采用和我一样的 7070 端口的话就不用作任何修改.

Chrome + AutoProxy

  • 安装 Chrome
运行下面的命令,添加证书
sudo wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
把下面的源添加到 /etc/apt/sources.list 文件中
deb http://dl.google.com/linux/deb/ stable non-free main
随后更新数据库
sudo apt-get update
安装 Chrome
sudo apt-get install google-chrome-unstable
  • 在 Chrome 下可以利用 Switchy 中实现类似 Autoproxy 的自动规则功能。
关于 Switchy 的使用,更详细的介绍可以看此文: https://autoproxy.org/zh-CN/node/73
1 下载 Chrome Switchy 插件 http://switchy.samabox.com/ 无法安装的话请从这里下载并安装:switchy_extension_1_6_3.zip


2.添加 Autoproxy 规则链接 http://autoproxy-gfwlist.googlecode.com/svn/trunk/gfwlist.txt

ProxyChains 

现在我们可以用 FireFox 及 Chrome 通过 SSH Tunneling 来访问之前无法访问的网站了,但有些程序本身不支持 Socket 5 代理,那么我们可以通过 ProxyChains 这工具来实现。

ProxyChains

ProxyChains 是一个类似于 windows 下 freecap 的软件,可结合 ssh tunneling 功能来实现翻墙。
安装
sudo apt-get install proxychains
配置,修改 /etc/proxychains.conf
# proxychains.conf  VER 2.0
#
#        HTTP, SOCKS4, SOCKS5 tunneling proxifier.
#

# The option below identifies how the ProxyList is treated.
# only one option should be uncommented at time,
# otherwise the last appearing option will be accepted
#
# Dynamic - Each connection will be done via chained proxies
# all proxies chained in the order as they appear in the list
# at least one proxy must be online to play in chain
# (dead proxies are skipped)
# otherwise EINTR is returned to the app
#
# Strict - Each connection will be done via chained proxies
# all proxies chained in the order as they appear in the list
# all proxies must be online to play in chain
# otherwise EINTR is returned to the app
#
# Random - Each connection will be done via random proxy
# (or proxy chain, see  chain_len) from the list
# this option is good for scans

dynamic_chain
#strict_chain
#random_chain

# Make sense only if random_chain
chain_len = 2

# Quiet mode (no output)
#quiet_mode

# Write stats about good proxies to proxychains.stats
#write_stats

#Some timeouts in milliseconds
#
tcp_read_time_out 15000
tcp_connect_time_out 10000

[ProxyList]
# ProxyList format
#       type  host  port [user pass]
#       (values separated by 'tab' or 'blank')
#
#
#        Examples:
#
#             socks5 192.168.67.78 1080 lamer  secret
#  http 192.168.89.3 8080 justu hidden
#   socks4 192.168.1.49 1080
#         http 192.168.39.93 8080
#
#
#       proxy types: http, socks4, socks5
#        ( auth types supported: "basic"-http  "user/pass"-socks )
#
#http  10.0.0.5 3128
socks5 127.0.0.1 7070
注意选 dynamic_chain
如何使用?
比如我们可以通过 proxychains 来运行 Twitter 客户端 pino ,如下。
proxychains pino &
就这么简单

另外通过 proxychains 来安装来自于 PPA 的软件可以起到增速的作用。
sudo proxychains apt-get install software-name

参考

如何使用 SSH Tunnel ( 隧道 ) ? http://w.riku.me/how_to_use_ssh_tunnel
用 SSH 代理为 PPA 增速 http://w.riku.me/blog/ubuntu/ppa
在 Freebsd 下用 autossh 自动登录并掉线重连的 ssh tunneling proxy server http://w.riku.me/freebsd/autossh
原文
------------------------------------------------------------------------------------------------------
通过autossh和证书实现SSH自动重连

以前一直使用GSTM管理翻墙的SSH连接,因为比较简单好用,可是当升到GNOME3之后,GSTM一直没有更新,于是选择使用了autossh。
autossh 其实就是在ssh的基础上增加了自动重连的功能,它基本适用各种ssh的参数(除了-f被autossh用作后台运行,并不会传送给 ssh)。但是当autossh 使用-f参数在后台运行时,有个缺点是无法输入密码,而且并没有像plink一样提供-pw参数,所以ssh在-f参数下无法连接至服务器。
这就需要让ssh通过证书免密码登录了。
在本地终端执行ssh-keygen指令,生成rsa密钥和公钥。

1
[red@blade ~]ssh-keygen
将生成的rsa公钥上传给服务器

1
[red@blade ~]$ ssh-copy-id -i ~/.ssh/id_rsa.pub user@server
通过ssh登录服务器,在服务器上修改/etc/ssh/sshd_config文件,取消以下2行的注释

1
2
#PubkeyAuthentication yes
#AuthorizedKeysFile .ssh/authorized_keys
最后在服务器上重启ssh服务

1
[red@bass ~]sudo service ssh restart
之后就可以通过autossh自动后台登录ssh并实现自动重连了

1
[red@blade ~]$ autossh  -f  -ND 7070 user@server
可以将命令保存成脚本,那样就更加方便了.
----------------------------------------------------------------------------------------

autossh在Ubuntu desktop上的配置

背景

ssh除了可以提供远程登录服务之外,还可以建立主机之间的网络隧道,尤其是可以提供SOCKS代理(传说中的ssh -D)。但用ssh命令建立的隧道可能会受网络的影响而中断,不能为用户提供持续的服务。autossh正好是解决上述问题的工具:为用户提供可靠的ssh隧道服务。
在使用autossh之前,我的做法是:首先,做一个shell脚本检查相应的ssh进程是否存在,如不存在,则重新启动ssh隧道;然后,将上述 脚本加入系统crontab,定时执行,例如1分钟1次。但是,用shell脚本检查有一个缺点:有时候,ssh进程虽然并没有退出,但ssh隧道已经不 能正常转发报文了,shell脚本难以发现这类情况。为了避免ssh进程存在、隧道假死的问题,可以采用定时重启ssh进程并重新建立ssh隧道的方法。 但重启间隔不好设置:间隔过短,导致ssh隧道用户频频掉线,影响用户使用;间隔过长,一旦隧道假死,在重启ssh服务之前会有较长的服务中断间隔。
autossh对ssh隧道的监控则更加有效。首先,在开始执行时,autossh首先创建ssh子进程,建立隧道。同时autossh作为父进 程,随时监控ssh进程是否退出,一旦退出则立即启动新的ssh隧道。autossh这种做法比crontab定时检查在失效恢复速度上更具有优势。其 次,autossh还会定期检查ssh隧道是否能够正确传输数据,如发现隧道假死,也会强制重启ssh,建立新的ssh隧道。

Ubuntu上的autossh

autossh在Ubuntu上的安装很简单,运行下面的命令即可:
apt-get install autossh
然而,Ubuntu下的autossh并没有包含相关的后台服务脚本。用户如果希望开机自动运行autossh需要自己写daemon脚本。 Ubuntu下写daemon脚本有两个选择,一种是写传统的/etc/init.d下的脚本,令一种就是Ubuntu特有的upstart脚本。
upstart是Ubuntu设计用来替换传统的SysV init的软件。upstart的daemon脚本除了更加简洁之外,还支持服务的自动唤醒(respawn)。这样autossh本身如果出错退出了,也会立即被upstart唤醒。避免autossh出错退出导致ssh隧道无法访问。
我写的autossh的upstart脚本文件如下(文件名是/etc/init/autossh.conf):
# autossh
 
description "autossh daemon"
 
start on runlevel [2345]
stop on runlevel [!2345]
 
respawn
respawn limit 5 60 # respawn max 5 times in 60 seconds
 
script
    export AUTOSSH_PIDFILE=/var/run/autossh.pid
    export AUTOSSH_PORT=10007:7
    export AUTOSSH_POLL=60
    export AUTOSSH_FIRST_POLL=30
    autossh -4 -N example.com -D 1080 -o BatchMode=yes -o StrictHostKeyChecking=no
end script
这样重启之后,autossh就会自动启动。手动启动、停止、重启autossh服务可以通过运行start、stop、restart等命令完成。

其他

1. ssh自动登录
autossh在后台执行ssh命令建立隧道时,需要设置好配置好本机的ssh证书,以及服务器上的authorized_keys文件,以实现ssh的自动登录。否则autossh将无法登录远程主机并建立隧道。相关说明参见网络上的教程
2. echo服务
上述autossh脚本中的AUTOSSH_PORT参数,是autossh用于判断ssh隧道健康状况专用的隧道链接,参数意义是:建立本地端口10007到远程服务器端口7的隧道,其他参数说明初次启动ssh时,在30秒后判断隧道链接情况,之后每60秒检查一次。
其中,远程服务器端口7,运行的是标准的TCP Echo服务。在Ubuntu上echo服务可以通过openbsd-inetd来实现,首先在远程服务器(注意:不是autossh所在的ssh客户端机器)上安装软件:
apt-get install openbsd-inetd
安装之后,inetd默认没有把echo服务激活,需要手动在/etc/inetd.conf配置文件中增加下面一行:
echo  stream tcp nowait root internal
重启inetd后,远程服务器的echo服务就正式上线了,可以供autossh判断网络隧道连通情况了。

from http://dipplum.com/2010/09/11/autossh-ubuntu-upstart-script/
-------------------------------------------------------------------------------

自动连接ssh -D的launchd配置

背景

与Ubuntu的upstart类似,Mac OS上提供了launchd作为后台服务的管理程序。ssh -D命令可以为用户提供sock5代理,但是每次访问网络之前,都要打开Terminal手动运行ssh命令是一件很烦的事情。加上网络条件不好,ssh 频繁退出,就更烦了。Linux下有autossh+upstart/init可以选择,Mac OS下就需要借助launchd了

配置Mac到远程ssh服务器的自动登录

为了将ssh -D变成launchd管理的后台服务,配置ssh自动登录是必须的。Mac下过程与Linux不太一样,首先打开Terminal,生成用户ssh证书:
sudo su
ssh-keygen
cat /var/root/.ssh/id_rsa.pub
然后把公钥上传到ssh服务器。注意:Mac OS下root的HOME被设置在了/var/root下。
ssh EXAMPLE.COM mkdir .ssh
scp id_rsa.pub EXAMPLE.com:.ssh/authorized_keys
 
# 测试公钥认证是否成功
ssh -o BatchMode=yes EXAMPLE.COM

生成launchd格式的plist文件

将下述ssh-d.plist文件放在/Library/LaunchDaemon/目录下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key>
      <string>localdomain.localhost.ssh-d</string>
    <key>ProgramArguments</key>
      <array>
        <string>/usr/bin/ssh</string>
        <string>-o</string>
        <string>BatchMode=yes</string>
        <string>-o</string>
        <string>CheckHostIP=no</string>
        <string>-o</string>
        <string>StrictHostKeyChecking=no</string>
        <string>-D</string>
        <string>1080</string>
        <string>-i</string>
        <string>/var/root/.ssh/id_rsa</string>
        <string>-vvvNnT</string>
        <string>root@EXAMPLE.com</string>
      </array>
    <key>KeepAlive</key>
      <true/>
    <key>RunAtLoad</key>
      <true/>
    <key>StandardOutPath</key>
      <string>/var/log/ssh-d-out.log</string>
    <key>StandardErrorPath</key>
      <string>/var/log/ssh-d-err.log</string>
  </dict>
</plist>
然后运行下面的命令后台启动ssh -D:
launchctl load /Library/LaunchDaemon/ssh-d.plist
如果出错需要调试,ssh进程的标准输出和标准错误输出保存在/var/log目录下的ssh-d-out.log和ssh-d-err.log文 件中。如果一切正常,则配置完毕,以后Mac启动后,ssh -D进程会自动启动,ssh退出后,launchd也会自动生成一个新的进程。

与autossh集成

如果通过fink和MacPorts或者其他方法安装了autossh,可以修改上述脚本中的ssh程序的路径为autossh的路径。并将autossh的参数按格式加入plist文件,这样,也能享受到autossh提供的隧道假死后自动重启功能。

延伸阅读

from http://dipplum.com/2010/09/12/launchd-plist-for-ssh-d/
-------------------------------------------------------------------

Remote Desktop connection using an SSH tunnel on the Android

Remote desktop connection using an SSH tunnel is a well known method to connect
to remote PCs when an SSH server available on the same network. This serves as
an alternative to VPN and is secure as all data is sent encrypted through the
ssh tunnel.
On my openSUSE laptop, I use the following command
to connect to the SSH server (sshserver) and create an tunnel between the
remote desktop port of my Windows XP machine(workpc) and the local port
3389.:
ssh -C -L 3389:workpc:3389 vimal@sshserver
The option -C enables compression and -L is used to specify the local
port that will be used for the remote desktop connection. IP addresses should
be used for workpc and sshserver if hostnames cannot be resolved.
Once connected, a remote desktop client like rdesktop or krdc can be
used to connect to the session. For example, using rdesktop the following
command can be used
rdesktop -f -k en-gb localhost:3389&
-f starts rdesktop in full screen mode, -k is used to specify the keyboard layout.
Okay, how to do this on the Android? I knew about the applications that can be
used for the tasks above. ConnectBot can do SSH connections and Remote RDP Lite
can be used for making a remote desktop connection. But I was skeptical if the
port forwarding can be done and also if the remote desktop would be any good on
a small screen – my Motorola Milestone. Here is how I got it to work
Install both the applications mentioned above. They are available in the Android Market.
Open ConnectBot and make the ssh connection:
vimal@sshserver
Type in and click done. If the SSH port is different, it can be specified as:
vimal@sshserver:portnumber
Once connected, click and hold on the connection in the hosts screen. You will
be presented with an option to 'Edit port forwards'
Access the menu and choose 'Add port forward' and fill in details similar to this:
Nickname: work
Type: Local
Source port: 3389
Destination: workpc:3389
Save it. Disconnect and connect again to make the port forward to come into effect.
Once connected, open Remote RDP Lite and make a connection as follows:
Host: localhost
Port: 3389
Go back and select @localhost or whatever you named it. You should get to
the login screen. The touch screen works and you can use it as the mouse and
the keyboard works too! The mouse functions are a bit tricky because of the
small screen. Here are some screenshots.

FROM: http://vimalkumarvelayudhan.com/2010/04/26/remote-desktop-connection-using-an-ssh-tunnel-on-the-android
-------------------------------------------------------------------------------------------------------------------

利用SecureCRT翻墙

所需条件:SecureCRT 或 Putty,一个国外 SSH 帐号
推荐:Firefox + Firefox 扩展 FoxyProxy (或其他浏览器)+ SecureCRT
SecureCRT 是共享软件,有汉化版,在此下载:http://down.51cto.com/data/10448/
SSH 帐号的来源可以有多种,最常见的来源是国外的虚拟主机帐号,如 DreamhostMediaTempleBluehost 等。
本文以 SecureCRT + Dreamhost + Firefox为例。
首先来配置 SecureCRT。点击菜单 File -> Connect 以打开连接对话框,点击对话框上部第三个按钮 New Session 以新建会话。在弹出来的会话属性设置对话框中设置会话名称。
选择左侧的选项分支 SSH2,设置 SSH 服务器详情。
选择左侧的选项分支 Port Forwarding,在右侧点击 Add 按钮,参照图片,设置本地端口转发。本文以 53817 为例,请改为您想要的端口,如7070。
点击 OK,完成会话设置并回到连接对话框,选中刚才添加的会话,单击 Connect,若前面的 SSH 服务器详情设置无误,则有弹出 New Host Key 对话框,提示是否保存服务器 key,单击 Accepet&Save(接受并保存),并在接下来的对话框中输入 SSH 帐户密码。
一切顺利的话,不用几秒钟,登录就可完成。现在可以在支持 Socks 代理的浏览器中设置本地代理了。按前文的设置,此时的本地 Socks 代理应为 localhost:53817 或 127.0.0.1:53817。设置好代理之后,可以试着访问 WordPress 的翻译项目页面,若一切无误,应该可以正常浏览该页面了。
Firefox + FoxyProxy 的设置不再以图片的方式详细介绍,相信熟练的 Firefox 用户可以稍做设置以实现对特定的地址调用该代理。为了方便起见,可以下载我的 FoxyProxy 设置文件,放置于 Firefox 的Profile 目录下。若该文件已存在,请先备份。
Maxthon、TheWorld、GreenBrowser 之类浏览器的代理设置不再在此赘述。
@Updated:
放弃了撰写 putty 的设置方法的计划,因为 putty 不能自动登录,不能自动重连。这两大缺点输给了上文提到的 SecureCRT 和下文要介绍的 MyEnTunnel。
谢谢 voidman 的提醒。若只需要建立 SSH Tunnel 翻墙,只需要 plink.exe 即可,但 plink.exe 是命令行工具,用起来不是那么方便。好在有 MyEnTunnel 这个 GUI 工具可以直接操作 plink.exe。先下载这两个可执行文件,将它们放在同一个文件夹下。运行 myentunnel.exe ,主要设置界面如下:
主要选项:
SSH Server – SSH 服务器地址
SSH Port – SSH 服务器端口
Username – 用户名
Passphrase – 密码
Port – 本地 SOCKS 代理端口
Connect on Startup – 运行时自动连接
Reconnect on Failure – 失败时重新连接
Enable Dynamic SOCKS – 启用动态套接字
这些选项中,前四个当然一定要填对了。为了实现我们的目的,一定要选择 Enable Dynamic SOCKS (启用动态套接字)并设置好转发端口 Port。设置好之后,点击 Connect,若系统托盘处的小锁从红色变成绿色,则连接已经建立了。这时可以点击 Hide,让它驻留在系统托盘。接下来的工作就只剩下设置浏览器的代理了。
----------------------------------------------------------------------------

PuTTY 中文教程

作者:柴锋   2006年11月
Web:http://chaifeng.com/blog/
email: putty-tutorial [0x40] chaifeng [0x2E] com
Links:
http://docs.google.com/View?docid=ajbgz6fp3pjh_2dwwwwt

更新记录

  • 2006-11-29
    初步完成想写的这些东西
  • 2007-06-11
    PuTTY 的最新版本到了0.6;修改了一下 SSH 隧道;添加了 SSH 反向隧道;添加了用 SSH 做代理服务器;
  • 2007-09-03
    补充了几个 FAQ
  • 2008-05-04
    很久没有更新过了,这次加上一个小技巧吧,如何安全、方便的使用 vnc,远程连接 vnc 不需要密码。
  • 2008-08-12
    刚刚在 lifehacker 看到 Google Docs 的几个小技巧 ,这篇文章终于有目录了 ^_^
  • 2009-04-11
    补充了一个 FAQ,如何保存登录的会话,下次登录还可以看到上次登录的界面。
    另外,昨天刚刚从 QCon Beijing 2009 的大会现场回来,祝贺这次 QCon 大会的成功召开。


序言

懒,是一个优点,有些时候还是要学一学才能会了的。 
                                                   —— 柴锋(1979-       ) 
我的这些文字是从这几年来的 PuTTY 使用经验中慢慢得来的,也不仅仅是介绍 PuTTY,还包括了一些相关的软件,比如:优秀的 FTP 工具 FileZilla、功能强大的 SFTP 客户端 WinSCP。
杂七杂八的乱说了一些,这里把大致内容罗列如下:
  • 最简单的使用,登录 SSH 主机
  • 中文乱码的处理
  • PuTTY 常用配置的说明
    • 复制、粘贴
    • 保存会话
    • 注销
    • 自动登录用户名
    • 自动设置环境变量
    • 设置代理服务器
    • 自动执行命令
    • 备份、删除 PuTTY 的设置
  • PuTTY 的 X11 转发
  • 如何用 PuTTY 建立 SSH 隧道
  • 如何用 PuTTY 建立反向的 SSH 隧道,像个特洛伊木马一样突破防火墙
  • 把 PuTTY 作为一个安全的代理服务器
    • 安全的上网不被嗅探
    • 避免 MSN 等聊天工具被监听
  • 怎样用 PSCP、PSFTP 安全的传输文件
    • 功能强大的 SFTP 客户端 WinSCP
  • 用 PuTTYgen 生成密钥,登录 SSH 主机不再需要口令
  • Pagent 代理密钥,每次开机只需要输入一次密钥口令
  • Plink 简单而又迅速的执行 SSH 主机上的程序
  • 常见问题
除了上面的这些,还夹杂了一些 PuTTY 使用上的技巧、服务器配置的一些安全建议。说起来这是一些有关 PuTTY 的使用教程,其实也就是 SSH 的参考教程,绝大多数的内容在其他系统或软件上也都是一样的。不同的是参数、配置、命令行之类的,只要会了一个,其他也就触类旁通了。

一些基本知识

如果你已经知道 SSH、Telnet、Rlogin 这是什么,就跳过这一部分,看下面的吧。
(以后补充,暂时空下)

简介

PuTTY 的官方网站:http://www.chiark.greenend.org.uk/~sgtatham/putty/,截止到 2006年11月,发布的最高稳定版本是 0.58 2007年6月,发布的最高稳定版本是 0.6。

PuTTY 是一个跨平台的远程登录工具,包含了一组程序,包括:
  • PuTTY (Telnet 和 SSH 客户端)
  • PSCP (SCP 客户端, 命令行下通过 SSH 拷贝文件,类似于 Unix/Linux 下的 scp 命令)
  • PSFTP (SFTP 的命令行客户端,类似于 FTP 的文件传输,只不过使用的是 SSH 的 22 端口,而非 FTP 的 21 端口,类似于 Unix/Linux 下的 sftp 命令)
  • PuTTYtel (仅仅是一个 Telnet 客户端)
  • Plink (命令行工具,执行远程服务器上的命令)
  • Pageant (PuTTY、PSCP、Plink 的 SSH 认证代理,用这个可以不用每次都输入口令了)
  • PuTTYgen (用来生成 RSA 和 DSA 密钥的工具).
虽然包含了这么多,但平时经常见到只是用 PuTTY 登录服务器,完全没有发挥出 PuTTY 的强大功能。
PuTTY 作为一个组件也存在于很多的软件中,比如 FileZilla、WinSCP
在后面的文字中,如非特别说明,默认的登录的协议是 SSH。毕竟用 PuTTY 主要就是登录 SSH 主机,用 Telnet、RLogin 没法体现出 PuTTY 的强大功能。

安装

下载页面在这里:http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
PuTTY 需要安装么?需要么?需要么?真的需要么?不需要。PuTTY 是一个准绿色软件,说它绿色是因为直接就能使用,完全没有任何的安装程序。准绿色是指 PuTTY 的所有配置都保存到了注册表,如果不记得备份注册表中的相关内容,下次重装机器所有配置就没了,而且配置也不方便用闪存盘随身携带。但是 PuTTY 的配置删除还是蛮方便的,运行时指定个参数 -cleanup 就可以清除 PuTTY 的所有配置信息。

第一印象,开始登录一台远程主机

运行 PuTTY 就可以看到下面这个界面

在这里输入服务器的 IP 或主机名,选择好登录协议,还有协议的端口,如果希望把这次的输入保存起来,以后就不需要再重新输入了,就在第4步输入好会话保存的名称,比如:mail-server,或者干脆就是主机的地址,点击保存就可以了。

最后点下面的 Open 按钮,输入正确的用户名和口令,就可以登录服务器了。

首次登录一台主机时

第一次登录时,会看到这个对话框

这是要告诉你登录的主机密钥指纹,点 Yes 就保存起来,以后就不会再弹出这个窗口,然后就正常登录。点 No 不保存,下次还是要提示你,然后也可以正常登录。如果一台主机我们只是临时登录一下,当然就是点 No 了。Cancel 就是取消,也就是取消了这次登录。
如果你曾经登录过这台主机,但是又弹出来这个对话框,可能有以下几种情形:
  • 主机重新安装了操作系统
  • 这台主机可能有多个IP,这次用的是另外一个 IP
  • 有其他不怀好意的主机来冒充,诱骗我们登录,窃取隐秘信息
前两个情形很常见,一般点 Yes 就行了。后面这个嘛……唔……唔……,点 No/Cancel,再去询问相关的主机管理人员。

又看到了中文乱码

成功登录主机后,输入命令,这……这……显示,又是乱码。唉,中文乱码是一个老生常谈的问题,提起来就头大。原因嘛,不外乎字符集、终端编码之类的,还是可以解决的。

PuTTY 的默认字体和字符集并不适合中文显示, 在窗口标题上点击右键,选择 Change Settings...

在打开的配置窗口左边选择 Appearance,在右边点 Font settings 里面的 Change 按钮,选择好中文字体,比如:宋体、新宋体之类的

字体选择好了,还要确定字符集。
选择配置窗口左边的 Translation,在右边的 Received data assumed to be in which character set 下拉列表中选择最后一个“Use font encoding”,最后点下面的 Apply 按钮就生效了。

重新执行命令 ls -l,就可以正常看到中文了

怎么还是乱码?

如果还是乱码的话,就执行以下命令,看看系统的字符集
echo $LANG $LANGUAGE

哦,原来系统的字符集是 UTF-8 呀。重新返回上面选择字符集的那一步, 选择配置窗口左边的 Translation,在右边的 Received data assumed to be in which character set 下拉列表中选择“UTF-8”

这下99%的情形下,汉字是不会有乱码了。最后,总之一下 PuTTY 中乱码的解决办法:
先看看系统的字符集,如果是 UTF-8 的,那就简单了,选择好中文字体,然后编码选择 UTF-8 就行了。
如果编码是 GB2312、GBK、GB18030,当然也包括 BIG5这些,在 PuTTY 的编码选择中看不到这些编码,那就选择最后一个“Use font encoding”,绝大部分情况下这样就没啥问题了,反正我是没碰到有什么例外的情况。
现在的 Linux 如果默认语言选择为中文,默认的编码就是 UTF-8 了。以前安装 Redhat AS 3 时,语言选择为中文,默认的编码是 zh_CN.gb2312, zh_CN.gb18030,好像从 AS 3 update 6 开始,包括现在的 AS4、AS5,中文的默认编码都成了 zh_CN.utf8。至于 Debian、Ubuntu 等等这些上面,好像一直都是 UTF-8。
至于是使用 UTF-8呢,还是用 GB2312、GBK 或者 GB18030呢?我个人还是倾向于 UTF-8。毕竟我们使用的大多数软件都是国外的,处理中文编码多多少少有些问题,PuTTY 自然也不例外。
下面的这个图上,我把终端编码修改为 zh_CN.utf8,然后也按照前面的所说的方法把 PuTTY 的字符集修改为 UTF-8。然后在终端中输入汉字“柴锋”,按左方向键,可以看到汉字显示很正常。

我重新把终端的编码修改为 zh_CN.gb2312,同样的,把 PuTTY 的字符集修改为最后一个“Use font encoding”。还是在终端上输入汉字“柴锋”,按下左方向键以后,会看到汉字乱码了。

至于用哪个编码,主要还是看领导的决定了,我们的领导就喜欢 GBK,连 GB18030 都不行。以前在用 Debian 的时候,好像默认都不支持 GBK 编码。这几年公司的开发在汉字编码问题上出过几次麻烦,还不就是在 ISO8859-1, GB2312/GBK/GB18030和UTF-8上折腾来折腾去。
给大家看一张 emacs 的截图,看看上面的这么多语言的文字共同显示,这个会是用 GB2312/GBK/GB18030 的编码么?

用 UTF-8 也不是为了要在一个屏幕上显示好几种不认识的文字,也不一定非要是跟国际接轨弄个外包给老外开发程序做个其他语言的界面让老外用,起码不要在那么多编码里折腾了,顶多两个 ISO8859-1 和 UTF-8。发发牢骚,下面继续……

在 PuTTY 里面怎样选中,复制和粘贴?

在 PuTTY 的窗口里面复制、粘贴可不能用 Windows 里的这些 Ctrl+C, Ctrl+Ins, Ctrl+V 这些快捷键,Ctrl+C 在控制台上可是终止当前的命令执行。
PuTTY 的选择、复制、粘贴这些操作都是通过鼠标来完成的。
在 Window-〉Selection 这里可以设置复制和粘贴的方式。

默认的 Action of mouse buttons (鼠标按键的功能)的选项是 Compromise,这种方式下选中有两种方式,一是直接用鼠标左键拖拉选中就可以了,二是用鼠标中键单击选中区域的开头,用滚动条拖拉到期望选中区域 的末尾,再用鼠标中键单击,就可以选中了。
选中以后,单击鼠标左键就把选中部分复制到剪贴板了。粘贴也很简单,单击鼠标右键。
Action of mouse buttons 的第一个选项是 Windows (Windows 方式的),鼠标中键的操作跟前面提到的一样。右键不是粘贴了,而是打开了右键菜单。

其实这个右键菜单在标题栏上点击,也都可以看得到。

第三个选项是 xterm (xterm 方式),这个跟默认的 Compromise 方式相反的,中键和右键的操作调换了一下,就不多说了。
下面那个 Shift overrides application's use of mouse 是和 Shift 键有关的。有些 Rogue Like 的程序,比如 mc、links、Lynx、VIM 等等,都支持鼠标操作,想在用鼠标在上面选择或粘贴就不行了。这个选项默认是选中的,在支持鼠标操作的 Rogue Like 界面下,按住 Shift 键,就可以像前面的那样用鼠标来选择、复制、粘贴了。
看下面的这个图片,用 Links 打开了 Google 的首页,用鼠标去选中 顶部中间的 Google,我们会发现,弹出了保存的对话框。

按住 Shift 键重新操作一次,哈哈,这次选中了。

在 Control use of mouse 里面还有个 Default selection mode (默认的选择模式),默认是 Normal,就像文字处理工具里这样的选择

另外一个是 Rectangular block(块选择方式),至于用哪种方式就看自己的选择了。


实时保存会话

这次更改配置参数了,关闭窗口后,下次使用还是要重新选择的,麻烦。
还是回到上面修改配置的哪个地方,选择左边的 Session,在右边选择要覆盖的会话名称,或者重新输入一个新的名称,点击 Save 按钮保存。

关于注销登录的一些事情

成功登录主机后,也能正常看到中文了。这样,我们就可以完成大部分的工作。最后要关闭窗口了,该怎么办呢?我见过很多人,包括我们公司负责专职维护的同事,都是直接点击窗口上的关闭按钮,完全没有理会弹出警告窗口,直接点击了 Yes。

这样做是不对的,首先这不是正确的注销方式,应该输入命令 exit 来正常注销; 其次直接关闭窗口后,你的登录其实还在服务器上,如果一连多次的这样强制关闭窗口,用命令 w 或者 who 命令查看时,可以看到很多的用户还在系统上登录,占用了系统的资源。最重要的是,你的这次登录可能只是为了启动一下 WebLogic 或者其他什么应用服务器,直接关闭窗口后,可能会导致你的业务在随后的几分钟内也被终止,这应该不是你所希望看到的吧。
如果上述的理由是每次要输入 exit 然后回车,比较麻烦。你可以用快捷键 Ctrl+d 来注销登录,一般情况下,快捷键一按窗口都直接关闭了,还省了两次鼠标点击。
在前面说道保存会话时,大家或许也注意到,下面有个 Close window on exit 有三个选项:
  • Always (不管怎样,窗口总是要关闭的)
  • Never (无论是否有程序还在运行,都不要关闭窗口)
  • Only on clear exit (这个是默认选中的,只有在本次登录中运行的程序都正常终止或者在后台运行,窗口才关闭)
有的程序在执行时,虽然在命令最后面加上 “&”就能放到后台运行。但是正常注销登录后,窗口没有被自动关闭,还能看到程序的输出,这时强制关闭窗口还是可以的。为了避免这种情形,可以使用 nohup 命令。
用法嘛就是: nohup 命令 命令参数,这样就可以了。

窗口保存的输出有点少,前面的都看不到了

执行了一个命令,输出了好多东西,但是默认的配置下,PuTTY只保存了最后200行的内容,满足不了我们的需求。
还是在标题栏上点右键选择 Change settings...,在配置窗口的左边选择 Window,修改右边的 Lines of scrollback,改大点,比如 20000、80000的

在上面的 Set the size of the window 里设置的是窗口显示的行数和列数,默认是 24 行、80 列,根据自己的需要来修改吧。
When window is resized 这个选项配置的是,当窗口大小发生改变时该采取什么动作。
  • Change the number of rows and columns(这个是默认的,改变窗口大小时,自动修改行数和列数)
  • Change the size of the font(这个是根据窗口的大小来修改字体的大小,窗口最大化的时候,字都是很大的)
  • Change font size only when maximised(只有在窗口最大化的时候才改变字体大小)
  • Forbid resizing completely(完全禁止改变窗口大小,一了百了)
在现代的 Unix/Linux 主机上,默认选项已经不存在任何问题了。如果是 Solaris 8 这样的老式 Unix 上最好用第2或第4个选项。
第3个选项嘛,要求你的屏幕不是宽屏的,选中这个选项以后,大家可以先把窗口往窄的缩一下,然后最大化窗口,哈哈,满足一下不是宽屏的虚荣心。
顺便说一下,在 PuTTY 中的前后翻页,与 Linux 终端一样,用 Shift+PageUp/PageDown 来上下翻页,而 Ctrl+PageUp/PageDown 则是一行一行的。

新建一个会话时,还有些东西再啰嗦一下

前面把如何用 PuTTY 登录一台主机到注销的过程聊了一遍,但是在新建会话时还是有些东西需要再啰嗦一下的。

保持连接,不要自动断开

在 Connection 里面有个 Seconds between keepaliaves,这里就是每间隔指定的秒数,就给服务器发送一个空的数据包,来保持连接。以免登录的主机那边在长时间没接到数据后,会自动断开 SSH 的连接。
默认输入 0 是禁用保持连接,在这里我习惯的设置了 10。
下面的那两个复选框都保持默认选中吧。

自动登录用户

在 Connection-〉Data 里面有个 Auto-login username,可以指定默认的登录用户。如果每次登录主机都是用同一个用户,不妨在这里设置一下。SSH、Telnet、Rlogin 这三种协议都支持,但不是所有的 Telnet 服务器支持自动登录用户

自动设置环境变量

还是前面的那个界面,下面有个 Environment variables,在 Variable 输入环境变量的名称,Value里设置上环境变量的值,登录主机后就会自动设置上,但是这个不一定能用,有些主机为了安全,可能会禁用这个特性,一旦登录 就会收到这样一个错误提示:
Server refused to set environment variables

设置代理服务器

这个经常用到,设置方法大同小异,注意选择好 Proxy type(代理服务器的类型)就可以了。
代理服务器的地址填写到 Proxy hostname 这里,Port 就是代理服务的端口(HTTP代理常用端口有 3128、8080,Socks5代理常用端口有 1080)
Exclude Hosts/IPs 这里是填写排除的主机地址和IP,有些地址不需要代理,就在这里填写。
有些代理需要认证,用户名填写到 Username,密码则填写到下面的 Password。

自动执行一个命令

在 Connection-〉SSH 里有个 Remote command,在这里面填写上远程服务器上的某个命令,比如:df,登录后就会自动执行。
我们在 Unix 上用 ssh 登录主机时用的命令 ssh,在 ssh 的最后面加上远程主机上的命令,就跟这个一样。
但是……,先别着急,一旦设置上这个选项,你会发现在登录成功后,窗口一下就关闭了,嘿,怎么啦?什么也没看见。
因为命令执行完毕的同时,本次 SSH 登录连接也随之关闭。

你可以把远程自动执行的命令修改成 sleep 10,然后重新登录,再看看效果。
登录成功后,没有出现命令提示符,10秒钟后,窗口自动关闭。这也验证了刚才我说的,命令执行完毕后,SSH 连接自动断开。
冰雪聪明的你一定会想到,如果每次登录主机,都是要重新启动一下 tomcat,那这里就可以填写上这样的命令:
export CATALINA_HOME="~/apache-tomcat-5.5.17";export JAVA_HOME="~/jdk1.5.0_07";export PATH=$JAVA_HOME/bin;$PATH ; cd $CATALINA_HOME/bin;./shutdown.sh;./startup.sh;tail -f $CATALINA_HOME/logs/catalina.out
(上面的命令是一行的哦)
先自动设置一下环境变量(前面有提到,服务器可能会禁用自动设置环境变量,为了保险起见,在这里设置了一下),然后进入 tomcat 的 bin 目录,用 shutdown.sh 停止 tomcat,然后再 startup.sh 启动 tomcat,最后 tail 命令持续观察 tomcat 的日志输出,不想看了,就直接 Ctrl+C 就可以终止 SSH 的会话了。
哈哈,是不是很方便?
不过前面提到的命令 sleep 10,只是建立了 SSH 连接,然后 10 秒钟后自动断开。是不是觉得很无聊没什么用途啊?其实这个命令配合后面提到的 Tunnels(隧道),可以自动保持隧道一定时间的开放,如果指定时间内(在这里就是 10 秒钟)隧道没有被使用,就自动关闭 SSH 连接和隧道。
如果选中了 Don't start a shell or command at all 就禁用了自动执行命令这一个特性,这个主要是配合 Tunnels (隧道)来使用的。因为有时候,我们只需要利用隧道建立一个 VPN,而并不需要登录上去执行命令。用这个方法建立好隧道以后,就一直开放了,除非自己手工关闭。

嗯,还有个问题哦,如果一次要执行的命令很多,该怎么办呢?嗯,给 PuTTY 用 -m 选项指定一个包含远程主机上执行的命令的文本文件。不过以后还会说到 Plink,就是专门做这个用的,慢慢来慢慢来。

数据自动压缩传输,变相的提高传输速率

还是前面的那个界面,Protocol options 里面有个 Enable compression,这个选项的意思就是传输时压缩数据,在连接速度不变的情况下,变相的提高了传输速率。一般的 SSH 服务器都会允许这个选项的,所以还是选中好了。

无需口令登录

在 Connection-〉SSH-〉Auth 这里面有两个需要了解的,以后在讲到 PuTTYGEN 和 Pagent 时会详细介绍的。
一个是 Allow agent forwarding,作用是允许私钥代理的转发。
另外一个是最下面的 Private key file for authentication,选择私钥认证文件。
这两个可以让你用 SSH 登录不用输入主机口令,但是私钥的口令还是需要输入的,如果使用了私钥代理 Pagent ,私钥口令也可以省略。再配合前面提到的自动指定用户名登录,可以实现自动登录主机。登录到主机上以后,用 SSH 登录另外一个同样配置了相同的 私钥认证的主机,也可以不用再次输入口令。
这些可以大大减轻了我们的重复工作,不用单调枯燥的输入用户名和口令,但是这样使用有个后遗症就是如果主机密码没有在另外一个地方记录下来的话,这个密码很快会忘记的,好处嘛,密码可以设置的很长很变态 XD。

X11 转发能够让你在 Windows 上使用 Linux 的程序

这里很简单,选中 Enable X11 forwarding 后登录主机,记得在我们本地运行 X 服务端程序(比如:免费好用的 Xming)。

然后在控制台直接输入 X 环境下运行的程序,比如:xlogo,我们就可以看到 Linux 上的GUI界面的程序在Windows桌面上打开了。
运行个复杂的,比如 gnome-session,这个是 GNOME 的启动命令,如果想打开 KDE 就是 startkde

这样跟在本地使用 X Window 几乎是一样的了,而且还是运行在 Windows 的桌面上呢,骗骗小 mm 还是不错的。或许你会问这样用跟 vnc 那还不一样了?答案是,不一样。如果网络环境不好,还是用vnc吧,否则迟钝的图形响应速度会让你抓狂的。
打开了 GNOME 桌面,怎么关闭呢?点菜单的注销吧。如果你点了关机,这可关不了你的Windows,关的是远程主机。

用 SSH Tunnels(SSH 隧道),突破防火墙

哇哦,突破防火墙!是不是忽然有了做黑客的感觉呢?呀!子弹,我躲——,身子往后仰,继续闪……,噢,肚皮被子弹蹭了一下。
简单的说一下,SSH 协议能够通过已经建立好的 SSH 加密链路来转发任意的网络连接,从而避免了网络中的明文传输,也就无法用一些 Sniffer 工具嗅探到我们的隐秘信息了。
先说一下大致的使用过程,登录到主机上以后,就可以建立好一个 SSH 隧道,这时在你的机器本地会开放一个端口,通过本地的这个端口访问,就相当于在主机上去直接访问。很像代理服务器吧,如果隧道另一端的端口是动态 的,SSH 隧道就是一个代理了,SSH 隧道的意思大致就是这个。通过 SSH 隧道,我们可以保证从我们这一段到主机那一端是安全的,不会被监听到。
说了这么多,实际演练演练就知道了。在 PuTTY 的 Connection-〉SSH-〉Tunnels 这里就是配置 SSH 隧道的。
Add new forwarded port 这里就是添加隧道转发端口的,其中 Source port 是隧道的源端口,也就是隧道的入口,连接隧道时要连接这个端口。Destination 这里是目的地,隧道的出口,输入的格式是: server:port。
还 要说明的一点是 SSH 隧道是有方向的,这个方向是由下面的单选按钮 Local/Remote/Dynamic 来决定的。如果下面的单选按钮选中的是 Local,那么 Destination 这里填写的目标是相对于远程主机而言,而非你的机器。这样的隧道可以称之为正向隧道,隧道的入口是在你的本地,出口在远程主机那一端。如果单选按钮选中的 是 Remote,那么目标地址就是相对与你的机器而言,而非远程主机。这样的隧道称之为反向隧道,隧道的入口是远程主机那一端,隧道的出口则是你的本地机 器。这与 Local 选项是相反的。而最后一个 Dynamic 则不用指明 Destination 目标地址,也就是说目标地址是动态的了,连入隧道时可以随意指定目标地址,而不像 Local/Remote 指明的固定目标地址,所以这样的隧道就成了变相的加密 socks5 代理服务器了。
看明白了么?是不是会有些糊涂?后面我会举个例子来详细说说的。

开始演练,我们现在建立一条到远程主机 guantouping 上端口 7001 的隧道,在 guantouping 上可以用 nc -l -p 7001 localhost 这条命令建立一个监听本地到端口 7001 的连接,这样确保无法从其他机器访问这台主机的端口,只能在 guantouping 这台主机上用 telnet localhost 7001 来连接。现在我的机器 IP 是 192.168.6.25,如果直接用命令 telnet guantouping 7001 访问的话,那么在主机 guantouping 上会看到这样的提示:
[taylor@guantouping taylor]$ nc -l -p 7001 localhost
invalid connection to [192.168.6.200] from (UNKNOWN) [192.168.6.25] 1926
在这个配置面板上, Source port 上填写 8080,也就是我们要通过本地的 8080 端口来进入 SSH 隧道, Destination 这里填上 127.0.0.1:7001,就表示被登录的主机 guantouping 访问该主机本地的 127.0.0.1:7001 这个端口。正常登录到主机 guantouping 以后,SSH 隧道就建立好了。在我的机器 192.168.6.25 上输入命令 telnet localhost 8080,输入一些东西,就会在 guantouping 上看到有响应。在这里我用的是 nc,看起来方便一点,telnet 也是一样的。

这 就是正向 SSH 隧道的一个例子,大家实地操作几次也就会明白了。最上面有个复选框是“Local ports accept connections from other hosts”,这个选项的作用是允许其他主机连接你机器上的隧道入口,默认情况下建立好隧道以后,只允许本地链接。只有选中这个复选框才允许其他主机连接 你的本地隧道入口。

象特洛伊木马一样建立一条 SSH 反向隧道

下 面要说的就是选中单选按钮 Remote 后建立的反向 SSH 隧道,这样的隧道做什么用呢?一般防火墙都是允许从内往外链接,而不允许从外到内的链接,除非在防火墙上做好nat或端口转发。现在,你在防火墙的内部, 但是又想让外面的人链接到你的机器上。防火墙厚厚的城门紧闭,外面的人进不来,只有你能从里面打开这扇防护严密的大门,就像一个特洛伊木马一样,你主动连 接出去建立一个反向的 SSH 隧道,然后外面的人就可以通过这个反向的 SSH 隧道轻松突破防火墙链接到的你的本地机器。看下面这个图:
在 Source port 这里填写 8080,也就是隧道的入口是端口8080,Destination 这里填写 localhost:7001,也就是隧道的出口是本地的 7001 端口,下面的单选按钮要选中 Remote,表示建立的隧道是个反向隧道,填写完毕别忘记点 Add 按钮,在上面就可以看到显示的是 R8080 localhost:7001。成功登录远程主机 guantouping 后,反向隧道就建立好了。在远程主机 guantouping 上输入命令 telnet localhost 8080 就可以连接到你的本地端口7001。


哈 哈,这样一个特洛伊木马般的反向 SSH 隧道就建立完毕了。我们在远程主机上连接 8080 端口,其实就连接到了我们本地机器的7001 端口了。上面共有两个复选框,我们提到了一个,已经说了,选中以后就允许其他机器连接隧道入口了。那第二个“Remote ports do the same (SSH-2 only)”,则是给反向隧道使用的,也就是说远程主机的那个反响隧道入口也做同样的事情,也就是允许其他机器连接远程主机上的反向隧道入口,不过一般情 况下这个选项都不会起作用的 ^_^。

把 PuTTY 作为一个安全的代理服务器来使用

这个简单,在 Source port 那里填写上 1080,Destination 这里空下不填,选中下面的 Dynamic,最后别忘了点 Add 按钮。
登 录远程主机后,一个代理服务器就建立好了,这个代理服务器的地址就是 localhost:1080,还是加密的哦。据说国外某著名的主机供应商就提供远程的 SSH 链接,通过这个方法我们就建立了一个加密的 socks5 代理,可以轻松绕过万恶的 GFW 去拥抱 Wikipedia,波~~~,来一口。

设置 PuTTY 的默认设置

每次登录主机,无一例外的修改字体,修改字符集,修改窗口的大小,指定私钥文件,允许 X11 转发,……
几台主机还好说,几十个上百个主机这样三天两头的设置也会让唐僧烦了的。
选中一个先前配置好的会话,点 Load 按钮。

然后修改Saved Sessions会话名称 和 Host Name 这里的主机地址,点Save

如果在 Saved Sessions 这里和上面的 Host Name 清空,点 Save 按钮,就可以把设置保存为默认设置。

备份 PuTTY 的设置

用 PuTTY 最不爽的就是,它把所有的设置都保存到注册表了,本来这不是什么问题。但是难免会重装一下机器,用下面的命令可以备份 PuTTY 的所有设置
regedit /e PuTTY.config.reg "HKEY_CURRENT_USER\Software\SimonTatham\PuTTY"

删除 PuTTY 的设置

如果只是在其他机器上临时用了一个 PuTTY,用完以后想删除 PuTTY 的配置,就在控制台里输入如下的命令:
putty.exe -cleanup

用 PuTTYgen 来生成密钥,以后可以不用密码登录服务器了

PuTTYgen 是密钥生成器,用来生成一对公钥和私钥供 PuTTY、PSCP、Plink、Pagent 来使用。
直接运行 PuTTYgen 可以看到如下的界面。

点击 Generate 按钮就开始生成一个公钥和私钥对,生成完毕后,点下面的 Save private key 就可以把私钥保存起来,扩展名是 .ppk 的文件。
Load 按钮可以把先前保存的私钥重新打开,然后做些修改,比如修改注释和私钥口令,或者把 PuTTY 格式的私钥转换为 OpenSSH 格式的。

开始用 PuTTYgen 创建密钥

单击 Generate 按钮,然后你会看到进度条上面有个提示“Please generate some radomness by moving the mouse over the blank area.”,意思就是让你用鼠标在空白区域随机移动。随着鼠标在空白区域的移动,进度条会一直走下去。停止移动鼠标,进度条也就停止了。那我们就移动鼠 标,直到进度条走满为止。

等进度条走完之后,会出现下面的界面

最上面那个大大的只读文本框里面是公钥,用来保存到 OpenSSH 的 authorized_keys 文件中,这个文件中的每一行都是一个公钥。默认情况下,这个文件位于 Linux 用户主目录的 .ssh/ 子目录中,如果文件和目录都不存在,可以直接创建。
但是创建的文件、目录和用户主目录($HOME, $HOME/.ssh, $HOME/.ssh/authorized_keys)的权限有个限制就是对除了本帐户的其他所有帐户都要求是只读的,否则的话,即使公钥、私钥都匹配 无误,也是无法登入系统的。这是 SSH 服务器的一个安全要求,因为如果别的帐户可以修改你的 authorized_keys 的话,恶意的增加一个公钥,那对方不用你的帐户口令也能以你的帐户登入系统了。对于一些特殊要求,你可以在 SSH 服务器的配置文件 sshd_config 中用指令
StrictModes no
来取消这个限制。在 sshd_config 的帮助手册中可以看到
     StrictModes
             Specifies whether sshd should check file modes and ownership of
             the user’s files and home directory before accepting login.  This
             is normally desirable because novices sometimes accidentally
             leave their directory or files world-writable.  The default is
             “yes”.
小技巧:每次修改 authorized_keys 这个文件时,你可以用如下的命令来修改,确保所有的文件属性和权限无误
mkdir -p $HOME/.ssh && touch $HOME/.ssh/authorized_keys \
&& chmod go-w $HOME $HOME/.ssh $HOME/.ssh/authorized_keys && vim $HOME/.ssh/authorized_keys
还 有一个要强调的是那个 Key comment,这是密钥的注释,一定要修改。因为这个密钥是给自己用的,所以最起码要输入自己的名字,用默认的注释很容易和其他人的密钥混淆的。如果担 心自己的密码忘记了,可以在后面加上密码提示,当然了,不要让别人用注释猜出你的密钥口令。比如,我可以把注释修改为
ChaiFeng [20061120] w.z.
后面的 w.z. 就是我的密码提示,能猜出来么?呵呵

输入注释,上面的公钥也会随之发生变化。
现在最重要的是,输入自己的密钥口令。就是 Key passphrase 和 Confirm passphrase 这个两个输入框。
如果不输入口令,直接保存私钥会看到这个提示。为了安全起见还是输入口令吧,要不任何人得到这个私钥都可以不用口令登入系统了。

最后单击 Save private key 来保存私钥吧,保存到自己认为安全的地方,比如存放到私人的 USB 闪存盘上。需要登录时,插上 USB 闪存盘。登录完毕后就可以把 USB 闪存盘取下来,哈哈,这样子就比较安全了。
大家也注意到了,还有个 Save public key 按钮,这个是保存 SSH2 格式的公钥,有些 SSH 服务器要求用这种格式的公钥文件。一般情况下,我们是不需要的,所以这里也就保存了。以后还想的话,就用 PuTTYgen 把私钥 Load 出来,然后再保存也可以。

用密钥登录服务器的流程

上面杂七杂八的说了一堆创建密钥时的事情,大家会不会已经有些乱了呢?我把这个过程再罗列一遍:
  1. 如果没有公钥/密钥对,就用 PuTTYgen 创建一个,已经有了就可以忽略这一步。一个公钥/密钥对可以用在不同的服务器上,所以也不需要重复创建,关键要有足够强健的密码和安全的存放。
  2. 象先前一样输入帐户名和口令登录到主机上。
  3. 输入如下命令,来编辑 authorized_keys 文件
    mkdir -p $HOME/.ssh && touch $HOME/.ssh/authorized_keys \
    && chmod go-w $HOME $HOME/.ssh $HOME/.ssh/authorized_keys && vim $HOME/.ssh/authorized_keys


  4. 这个文本框里的公钥粘贴到 vim 中去,需要说明几点:这个文本框里的内容是一行的,粘贴到 vim 中时,别忘了按字母 o 这个键,否则的话,粘贴进去后,开头的 ssh-rsa 会变成 sh-rsa,为什么呢?哈哈,想想吧。
    为什么不按字母键 i 呢?这个在 vim 中不就是插入么?原因是我很懒,按字母 o,我可以节省一次按回车键。虽然按大写 O 也行,那我不是还得再按一下 Shift 键么?
    别忘了,在 PuTTY 中默认的粘贴可是按鼠标右键哦,然后按一下 ESC 键,然后输入 :wq 保存退出,等等,大家先别着急的输入 :wq,既然输入冒号还得按下 Shift 键,那我们就干脆直接两下大写的字母 Z,也就是 ZZ。怎么样?vim 也一样保存退出了吧。这次又节省了一次按键和两次寻找字母的移动,把懒得优良传统再一次在实践中发扬光大。
  5. 如果已经有了私钥,第4步里的那个公钥忘记保存了,就用 PuTTYgen 把这个私钥 Load 上去,然后重新复制一下公钥吧。
  6. 在 PuTTY 的配置 Connection->SSH->Auth 这里面,指定上私钥,然后记得保存 Session,以后就不需要重复这一步了。
  7. 最好也指定上自动登录的用户名,还记得这里吗?
  8. 开始登录吧,这次你会看到一个不同于以往的登录提示

    现在输入的口令可不是主机上这个账户的口令了,而是先前创建的这个密钥的口令。以后不管这个账户的口令是什么,即使再复杂,也和我们没关系了。只要这个账 户的 $HOME/.ssh/authorized_keys 文件中,有我们的公钥,我们就随时用匹配的私钥都可以登录了。配合后面提到的 Pagent,我们连输入密钥口令这一步也可以忽略过去。
  9. 登录成功了,别忘了按 Ctrl+d 注销哦。
以后这些步骤就不需要再重复了,只需要打开 PuTTY 后,双击一下保存的会话名称,输入密钥口令。

Pagent 加载密钥,每次开机后只需要输入一次密钥口令

终于轮到 Pagent 出场了,双击一下 Pagent.exe,嗯,没反应?再双击一下,咦?出来个提示,说已经运行了。

看看右下角吧,在这里呢

双击一下 Pagent 的图标,出来这样一个界面。很简洁的,Add Key 是添加私钥,Remove Key 是把选中的私钥从 Pagent 中卸载了。

好,现在单击 Add Key 按钮添加私钥,我把这个演示用的私钥保存到 C:\ 了

然后会出现输入密钥口令的对话框,输入正确的密钥后,单击 OK

这时,在 Pagent 的窗口中就能看到我们的私钥已经装载上去了。

现在打开 PuTTY,选择先前保存的 Session,双击一下。只要自动登录用户名设置上,主机上改帐户的 authorized_keys 文件里也有匹配的公钥。哈哈,发现没有?完全不需要口令,我们已经登录到系统了。
在 Pagent 的图标上点右键,也可以快捷的选择已经保存的会话。

建议大家把 Pagent 放到启动组里面,这样每次一开机,Pagent 自动运行,然后我们只需要把私钥装载一下,然后我们就可以一直享受自动登录系统的乐趣了。再配合上以后会讲到的 Plink、PSCP 这些,我们可以实现很多工作的自动化进行。完全不需要每次输入用户名、口令、输入又长又多的命令,再做一些烦躁的文件备份,最后还得记得注销系统,难道不 觉得麻烦么?这一切烦恼很快就会远离我们了,继续往下看吧。
(不用密码登录putty
1. 打开PUTTYGEN.exe 生成公私密钥。
2. 保存private key在本机(一个.ppk文件),注意此处不要填passprase,我们的目的本就是不想输密码。
3. 复制public key内容,粘贴到服务器你的用户目录下的 .ssh/authorized_keys,没有该文件的话请自行创建。
4. chmod 600 .ssh/authorized_keys
chmod g-w .ssh .ssh/authorized_keys 不改权限可能登不了。
5. 在putty中导入私钥。
相关截图:



from http://soido.org/blog/843)

用 SSH 来传输文件

PuTTY 提供了两个文件传输工具
  • PSCP (PuTTY Secure Copy client)
  • PSFTP (PuTTY SFTP client)
PSCP 通过 SSH 连接,在两台机器之间安全的传输文件,可以用于任何 SSH(包括 SSH v1、SSH v2) 服务器。
PSFTP 则是 SSH-2 中新增的特性,使用的是新的 SFTP 协议,使用上与传统的 FTP 类似。事实上 PSCP 如果发现 SFTP 可用,PSCP就会使用 SFTP 协议来传输文件,否则还是 SCP 协议。PSFTP 与 PSCP 相比,PSFTP 的优点是可以与服务器进行交互,遍历服务器上的文件系统,在一个会话中上传或下载多个文件。而 PSCP 只能一次传输一个文件,传输完毕后立刻终止会话。

PSCP 的使用

在控制台直接执行 pscp 可以看到帮助
C:\>pscp
PuTTY Secure Copy client
Release 0.58
Usage: pscp [options] [user@]host:source target
       pscp [options] source [source...] [user@]host:target
       pscp [options] -ls [user@]host:filespec
Options:
  -V        print version information and exit
  -pgpfp    print PGP key fingerprints and exit
  -p        preserve file attributes
  -q        quiet, don't show statistics
  -r        copy directories recursively
  -v        show verbose messages
  -load sessname  Load settings from saved session
  -P port   connect to specified port
  -l user   connect with specified username
  -pw passw login with specified password
  -1 -2     force use of particular SSH protocol version
  -4 -6     force use of IPv4 or IPv6
  -C        enable compression
  -i key    private key file for authentication
  -batch    disable all interactive prompts
  -unsafe   allow server-side wildcards (DANGEROUS)
  -sftp     force use of SFTP protocol
  -scp      force use of SCP protocol

C:\>
可以看出 PSCP 的使用是很简单的,把常用的几个选项说一下:
  • -q 安静模式,传输文件时什么也不显示,否则会显示出文件的传输进度,默认是关闭的
  • -P port 指定服务器的 SSH 端口,注意这个是大写字母 P,默认是 -P 22,如果主机的 SSH 端口就是 22,就不用指定了
  • -l user 指定以哪个用户的身份登录主机,如果没有指定,则 PSCP 会在 PuTTY 保存的同名 Session 中获得默认的用户名称。用户名称也可以和主机名称写在一起,用 @ 分割开,比如:username@server
  • -pw passwd 指定登录时所用的口令为 passwd
  • -i keyfile 就是指定登录时所用的密钥文件
  • 最后面指定的主机名也可以是 PuTTY 中保存的 Session 名称。比如我们在 PuTTY 中保存了一个名为 foobarserver 的会话,而我们所在的网络又的确没有名为 foobarserver 的主机名称。而在这个 foobarserver 会话中保存的主机名称是 demo-server,保存的自动登录的用户是 taylor。那么用命令
    pscp c:\autoexec.bat foobarserver:backup/
    就把本地的 c:\autoexec.bat 复制到了主机 demo-server 上的用户 taylor 所在的主目录下的 backup 子目录中(这个路径可能是 /home/taylor/backup

所以 PSCP 大致用法的例子就是:
pscp -P 22 -i c:\path\your-private-key.ppk -C username@server:/remote/path/
下面还是用一些实例来说明会比较简单一些:
把本地的 C:\path\foo.txt 复制到远程主机 192.168.6.200 的 /tmp 目录下
pscp c:\path\foo.txt 192.168.6.200:/tmp
把本地的 C:\path\foo.txt 复制到主机 192.168.6.200 的 /tmp 目录下,但是以主机上的用户 taylor 的权限执行
pscp c:\path\foo.txt taylor@192.168.6.200:/tmp
或者是
pscp -l taylor c:\path\foo.txt 192.168.6.200:/tmp
把本地的 C:\path\foo.txt 传送到主机 192.168.6.200 的 /tmp 目录下,但是主机的 SSH 端口是 3122
pscp -P 3122 c:\path\foo.txt 192.168.6.200:/tmp
把本地的 C:\path\foo.txt 复制到主机 192.168.6.200 的用户 taylor 的主目录下
pscp c:\path\foo.txt taylor@192.168.6.200:.
把主机 192.168.6.200 上的用户 taylor 主目录下的所有 *.tgz 文件拷贝到本地的 c:\backup 目录中,如果 SSH 版本是 SSH v1,那这个命令就会出错。
pscp taylor@192.168.6.200:*.tgz c:\backup

再来看看 PSFTP

在控制台执行命令 psftp -h,可以得到 psftp 的帮助
C:\>psftp -h
PuTTY Secure File Transfer (SFTP) client
Release 0.58
Usage: psftp [options] [user@]host
Options:
  -V        print version information and exit
  -pgpfp    print PGP key fingerprints and exit
  -b file   use specified batchfile
  -bc       output batchfile commands
  -be       don't stop batchfile processing if errors
  -v        show verbose messages
  -load sessname  Load settings from saved session
  -l user   connect with specified username
  -P port   connect to specified port
  -pw passw login with specified password
  -1 -2     force use of particular SSH protocol version
  -4 -6     force use of IPv4 or IPv6
  -C        enable compression
  -i key    private key file for authentication
  -batch    disable all interactive prompts

C:\>
用法与 PSCP 大同小异,虽然有个 -load 选项,其实这个没啥用,后面用主机名的时候,与 PSCP 一样直接用上会话名称就可以了。
用 PSFTP 登录到服务器上以后,操作与 FTP 差不多,这里简单的说一下吧:
  • open 登录主机
    open [username@]<sessname|hostname|ip> [port]
    比如:
    • open taylor@demo-server 3022
      就是以用户 taylor 的身份,登陆到主机 demo-server 上,SSH 端口是 3022
    • open demo-server
      登陆 demo-server,这里的 demo-server 可以是PuTTY 中已经保存的会话名称,也可以是主机的名称,如果主机名称与会话名称相同,以会话名称为准。
  • close 关闭 SFTP 连接
    这个没啥说的,close 就关闭了 SFTP 连接
  • quit 结束本次的 SFTP 会话
    也没啥用法,就是关闭了 PSFTP 这个程序
  • help [command] 帮助
    直接打 help 就可以看到帮助指令,后面指定上 一个命令就可以查看该命令的帮助,比如: help open
  • cd [directory] 改变当前目录
  • pwd 察看当前目录
  • lcd [directory] 改变本地目录
  • lpwd 察看本地当前目录
  • get [-r] <filename|directory> 从服务器下载一个文件/目录,这个命令不能用通配符,参数 -r 可以递归下载整个目录
  • put [-r] <filename|directory> [dest] 把文件/目录上传到服务器,这个命令不能用通配符,参数 -r 可以递归上传整个目录
  • mget [-r] <filename|directory> 从服务器下载一批文件/目录,可以用通配符,-r 的含义与 get 一样
  • mget [-r] <filename|directory> [dest] 把一批文件/目录上传到服务器,可以用通配符,-r 的含义与 put 一样
  • reget [-r] <filename|directory> 从服务器续传下载一个文件/目录,这个命令不能用通配符,-r 的含义与 get 一样
  • reput [-r] <filename|directory> [dest] 把一批文件/目录续传上传到服务器,这个命令不能用通配符,-r 的含义与 put 一样
  • dir [directory] 列目录
  • ls 和 dir 一样
  • chmod [file|directory] 改变文件的权限,与 Unix 的 chmod 命令类似
  • del <filename> 删除文件,要注意的是 del 只能删除文件
  • rm 与 del 一样
  • mkdir <new-directory-name> 创建一个目录
  • rmdir <directory> 删除一个空目录,只有空目录才可以被删除
  • mv <source-file|source-directory> <dest-file|dest-directory> 改名/移动。如果源和目的都是文件或目录,则是改名。如果目的是目录的话,则是移动。
  • ! 在本地命令前加一个感叹号,就可以直接执行

其他可选的 SFTP 客户端

FileZilla : http://filezilla.sf.net
WinSCP : http://www.winscp.net

用 Plink 更方便快捷的执行远程主机上的命令

Plink 是 PuTTY 的命令行连接工具,主要用于自动化工作的处理。
直接在控制台执行 plink,可以看到 Plink 的帮助
C:\>plink
PuTTY Link: command-line connection utility
Release 0.58
Usage: plink [options] [user@]host [command]
       ("host" can also be a PuTTY saved session name)
Options:
  -V        print version information and exit
  -pgpfp    print PGP key fingerprints and exit
  -v        show verbose messages
  -load sessname  Load settings from saved session
  -ssh -telnet -rlogin -raw
            force use of a particular protocol
  -P port   connect to specified port
  -l user   connect with specified username
  -batch    disable all interactive prompts
The following options only apply to SSH connections:
  -pw passw login with specified password
  -D [listen-IP:]listen-port
            Dynamic SOCKS-based port forwarding
  -L [listen-IP:]listen-port:host:port
            Forward local port to remote address
  -R [listen-IP:]listen-port:host:port
            Forward remote port to local address
  -X -x     enable / disable X11 forwarding
  -A -a     enable / disable agent forwarding
  -t -T     enable / disable pty allocation
  -1 -2     force use of particular protocol version
  -4 -6     force use of IPv4 or IPv6
  -C        enable compression
  -i key    private key file for authentication
  -m file   read remote command(s) from file
  -s        remote command is an SSH subsystem (SSH-2 only)
  -N        don't start a shell/command (SSH-2 only)

C:\>
看上去 Plink 的使用方法、参数与PSCP、PSFTP都很类似。
  • -P port 指定服务器的 SSH 端口,注意这个是大写字母 P,默认是 -P 22,如果主机的 SSH 端口就是 22,就不用指定了
  • -l user 指定以哪个用户的身份登录主机,如果没有指定,则 PSCP 会在 PuTTY 保存的同名 Session 中获得默认的用户名称。用户名称也可以和主机名称写在一起,用 @ 分割开,比如:username@server
  • -pw passwd 指定登录时所用的口令为 passwd
  • -i keyfile 就是指定登录时所用的密钥文件
  • -m file 如果执行的命令很多的话,可以把命令写到文件中,然后用这个参数来指定
还是用一些实际的例子来说明一下 Plink 吧
还记得前面说到 PuTTY 的自动执行命令那个配置么?在说到那个配置的时候,我们演示了一个简单的 Tomcat 重新启动的命令,这个命令是要写在 PuTTY 的 Remote command 里面去。现在我们用 Plink 来实现同样的功能:
假设连接的主机是 192.168.6.200,SSH 的端口是 3022,用户是 taylor:
plink -P 3022 taylor@192.168.6.200 export CATALINA_HOME="~/apache-tomcat-5.5.17";export JAVA_HOME="~/jdk1.5.0_07";export PATH=$JAVA_HOME/bin;$PATH ; cd $CATALINA_HOME/bin;./shutdown.sh;./startup.sh;tail -f $CATALINA_HOME/logs/catalina.out
如果在 PuTTY 中保存了一个名为 192.168.6.200 的会话,注意,这个会话的名称与主机 IP 一样,在会话中已经正确保存了端口 3022,指定了默认的用户是 taylor,现在这个命令就可以简化为:
plink 192.168.6.200 export CATALINA_HOME="~/apache-tomcat-5.5.17";export JAVA_HOME="~/jdk1.5.0_07";export PATH=$JAVA_HOME/bin;$PATH ; cd $CATALINA_HOME/bin;./shutdown.sh;./startup.sh;tail -f $CATALINA_HOME/logs/catalina.out
用 date 命令查看一下主机上的时间,并且格式化输出:
plink 192.168.6.200 date "+%F %T"
大家实际执行一下命令看看,会发现,这个命令并没有返回我们期望的结果,而是返回了一个错误:
C:\>plink 192.168.6.200 date "+%F %T"
date: too many non-option arguments: %T
Try `date --help' for more information.
可是在服务器上直接执行命令 date "+%F %T",的确是正确无误的,哪里出了问题呢?这是因为Windows的控制台会把两个双引号之间的字符串作为一个参数传递给被执行的程序,而不会把双引号也传递给程序。我们做这样一个小小的实验来说明一下这个问题:
比如在 c:\tmp 文件夹里建立三个文件夹,名称分别为:"foo"、"bar"、"foo bar"。然后在 foo 这个文件夹里面建立一个名为“foo.log”的空文件,在“bar”这个文件夹里建立一个名为“bar.log”的空文件,在“foo bar”这个文件夹里建立一个名为“foo-bar.log”的空文件。
然后在控制台下进入 c:\tmp 这个文件夹,执行如下命令:
dir foo bar
结果是列出“foo bar”这个文件夹里的内容,还是分别列出“foo”和“bar”文件夹里的东西呢?正确答案是后者。
要想正确列出“foo bar”文件夹里的东西,就需要用双引号把"foo bar"引起来
C:\tmp>dir foo bar
 Volume in drive C is System
 Volume Serial Number is 9C51-A51C

 Directory of C:\tmp\foo

2006-11-22  09:48    <DIR>          .
2006-11-22  09:48    <DIR>          ..
2006-11-16  11:58                 0 foo.log
               1 File(s)              0 bytes

 Directory of C:\tmp\bar

2006-11-22  09:48    <DIR>          .
2006-11-22  09:48    <DIR>          ..
2006-11-16  11:58                 0 bar.log
               1 File(s)              0 bytes
               2 Dir(s)   1,107,345,408 bytes free

C:\tmp>dir "foo bar"
 Volume in drive C is System
 Volume Serial Number is 9C51-A51C

 Directory of C:\tmp\foo bar

2006-11-22  09:48    <DIR>          .
2006-11-22  09:48    <DIR>          ..
2006-11-16  11:58                 0 foo-bar.log
               1 File(s)              0 bytes
               2 Dir(s)   1,107,345,408 bytes free

C:\tmp>
说 到这里,就会明白上面的那个命令 plink 192.168.6.200 date "+%F %T" 其实在主机上执行的真实命令是 date +%F %T,而不是命令行中指定的 date "+%F %T"。不过还好,Windows 的控制台可不认得单引号,所以上面那个命令的正确用法应该是:
c:\>plink 192.168.6.200 date '+%F %T'
2006-11-22 09:39:57
我经常需要登录到服务器上把 ADSL 重新拨号,可以把下面的命令写到一个文本文件中,比如保存到了 C:\adsl-restart.command.txt
echo "stoping..."
/sbin/adsl-stop
echo "starting..."
/sbin/adsl-start
echo "done."
/sbin/adsl-status
然后执行如下命令:
plink -m c:\adsl-restart.command.txt root@192.168.6.251
我经常要查看 Tomcat 的运行日志
plink taylor@192.168.6.200 tail -f ~/apache-tomcat-5.5.17/logs/catalina.out
每天都要看服务器上的剩余空间,就用这个命令:
plink taylor@192.168.6.200 df -k
假 设 www.chaifeng.com 连接着另外一个网段 10.204.26.0,有台内网IP 为 10.204.26.21 的 Solaris 8主机只能用 telnet 登录,为了防止被监听,我们可以用 Plink 建立一个隧道,隧道开放 120 秒钟,如果隧道没有被使用,就自动断开连接,然后我们在本地就可以用命令 telnet localhost 2623 的安全登录那台 Solaris 8 主机了。
plink -L 2623:10.204.26.21:23 www.chaifeng.com sleep 120
在主机 www.chaifeng.com 上正在运行着 tor,默认的监听地址是 127.0.0.1:9050,用 Plink 建立一个隧道,然后浏览器上配置代理服务器为 127.0.0.1,端口是 9050,这样就能够安全的使用 tor 代理了,不用担心从我们的机器到主机 www.chaifeng.com 有被监听的可能了。
plink -C -N -L 9050:127.0.0.1:9050 taylor@www.chaifeng.com
结合上 PSCP 我们还可以完成文件的每天备份
plink taylor@192.168.6.200 tar jcf $(date '+documents.%F.tar.bz2') ~/documents
pscp taylor@192.168.6.200:$(date '+documents.%F.tar.bz2') c:\backup\
plink taylor@192.168.6.200 rm -f $(date '+documents.%F.tar.bz2')
如果把这些常用的操作写成批处理文件,到时候要重启一下 Tomcat,或者马上察看一下 Tomcat 日志,再或者只是要把 ADLS 重新拨号以下,只需要用鼠标一双击这个批处理文件,稍等一下就自动完成了。不比你打开 PuTTY,登录到服务器上,然后再一个一个的执行命令,最后还得注销来的方便快捷么?再懒一些,把自动备份的批处理放到计划任务里面,每天定时完成,哈 哈,有时间上网找些好玩的东西了,不用每天忙于这些繁杂重复的命令中了。

用假象去迷惑敌人

如果我说 Google 的服务器也开放了 SSH,但是只有特定的 IP 可以连接上去,不信么?(声明:下面的图片都未经修改,我以 Google 的名义发誓,绝对没有 PS)


知道是怎么回事么?

Tips(小技巧)

安全、方便的使用 VNC,远程连接 VNC 不需要密码
有 关 VNC 的主题按理说不应该写在这里,可是通过一点小小的技巧,可以让我们安全、方便的使用 VNC。我们多数情况下用 Windows 远程登录 Linux 桌面的方法不外乎 X11 forwarding 和 VNC,有关 X11 转发的内容参照前面的部分,还有关于 X11 转发和 VNC 哪个方便,这里就不再啰嗦说这些了,自己试一试就知道了。
在远程机器上启动 vnc 服务的方法很简单,直接使用命令 vncserver 了。如果是第一次使用这个命令,还会提示输入一个口令。注意了,这个口令是用来远程连接 VNC 服务端用的,不是登录口令,着两个口令可不一样。如果想修改 vnc 的连接口令,使用命令 vncpasswd 就可以搞定,用法和 passwd 一样。哎哎,等等。标题上不是写的“远程连接 VNC 不需要密码”么?为什么这里还是需要连接密码?不要着急,慢慢听我讲。前面说的方法就是最常用的方法了,既然连接 VNC 的时候需要密码,那就带来一个老问题。密码太简单了,容易被暴力破解掉。密码太复杂了,人脑毕竟不是电脑,记不住。但是呢,为了安全,密码还是要设置的长 一点,我们可以使用一些其他工具帮助我们管理这些又臭又长的密码,比如 KeePass。
现在要说的是,我们可以把 VNC 的连接密码设置的好长好复杂,而且我们不用记,连接 VNC 的时候还不需要口令,不用担心暴力破解等等。我们需要做如下四步操作:
一、 在本地机器上,用参数 /listen 来启动 vncviewer,这个参数对于 RealVNC、TightVNC、UltraVNC 的客户端都一样。也就是要把 VNC 客户端启动在监听模式下,我们要让 VNC 服务器主动连接我们,这样我们就不需要 VNC 的连接口令了。
vncviewer /listen
二、创建一个 PuTTY 的反向隧道,源端口 5500,目标 localhost:5500,具体操作看前面的部分,别忘记点“Add”按钮哦。这个 5500 端口就是 vncviewer 的默认监听端口。

三、在远程服务器上用命令 vncserver 启动 VNC 服务,如果前面已经启动 VNC 服务了,就忽略这一步。
四、关键命令哦,在远程服务器上执行命令
vncconfig -display :1 -connect localhost
说 一下两个个关键参数,一个是 display 后面的 :1 ,这是连接到第一个 vnc 实例上。另一个就是 connect 参数后面的 localhost,既然我们是在远程机器上输入的这个命令,那很显然,连接的就是远程机器。别忘了,我们在此之前设置了反向的 SSH 隧道,连接远程机器的本地 5500 端口,其实连接的就是我们自己机器的 5500 端口。
哈,然后你就会发现什么密码也不用输入,就直接连接上远程的 VNC 服务了。不过呢,这四步操作确实有些麻烦,懒人的第一要旨就是能有多懒就要多懒。
第一步操作我们可以在 Windows 的启动菜单你里放一个 vncviewer 的快捷方式,别忘了 /listen 参数。
第二步操作可以直接保存到 PuTTY 的会话里面,参考前面的内容。
第三步就没啥子好说的,只要机器没有重启过,这个 VNC 服务就一直能用。
第 四步的这个命令,我们可以在 PuTTY 的 Connection->SSH 的选项里的 “Remote command” 里填写上 “vncconfig -display :1 -connect localost” ,然后同样也是保存到 PuTTY 的会话里。以后只要双击一下那个 PuTTY 的会话,我们的 VNC 窗口就会自动打开。
第二步和第四步操作也可以用一个命令来代替,如下:
plink.exe -R 5500:localhost:5500 guantouping "vncconfig -display :1 -connect localhost"
命令参数中的那个 “guantouping” 是 PuTTY 保存的会话名,也可以是远程机器主机名,把这个命令做成一个快捷方式,双击直接打开 VNC。

FAQ(常见问题)

我在 PuTTY 官方网站下载的,可是执行 PuTTY、Pagent、PuTTYgen 时总是出错,而命令行执行的这几个却没问题
这种情形我也碰到过,一个解决的办法就是去下载最新版,或许你碰巧下载的是旧版本。另外一个解决办法就是,创建三个扩展名为 .manifest 的文本文件,然后把这三个文件复制到 PuTTY 的目录中,文件内容分别如下:
把下面的内容复制到记事本中,文件名保存为:PAGEANT.exe.manifest
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- This is present purely to make Visual Styles in XP work better.
     See 20020104174954.A12067@imsa.edu. -->
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
   type="win32"
   name="Pageant"
   version="0.0.0.0" processorArchitecture="x86"/>
   <dependency>
   <dependentAssembly>
        <!-- Load Common Controls 6 instead of 5 to get WinXP native-
             looking controls in the client area. -->
        <assemblyIdentity type="win32"
             name="Microsoft.Windows.Common-Controls"
             version="6.0.0.0"
             publicKeyToken="6595b64144ccf1df"
             language="*"
             processorArchitecture="x86"/>
   </dependentAssembly>
   </dependency>
</assembly>
把下面的内容复制到记事本中,文件名保存为:PUTTY.exe.manifest
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- This is present purely to make Visual Styles in XP work better.
     See 20020104174954.A12067@imsa.edu. -->
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
   type="win32"
   name="PuTTY"
   version="0.0.0.0" processorArchitecture="x86"/>
   <dependency>
   <dependentAssembly>
        <!-- Load Common Controls 6 instead of 5 to get WinXP native-
             looking controls in the client area. -->
        <assemblyIdentity type="win32"
             name="Microsoft.Windows.Common-Controls"
             version="6.0.0.0"
             publicKeyToken="6595b64144ccf1df"
             language="*"
             processorArchitecture="x86"/>
   </dependentAssembly>
   </dependency>
</assembly>
把下面的内容复制到记事本中,文件名保存为:PUTTYGEN.exe.manifest
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- This is present purely to make Visual Styles in XP work better.
     See 20020104174954.A12067@imsa.edu. -->
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
   type="win32"
   name="PuTTYgen"
   version="0.0.0.0" processorArchitecture="x86"/>
   <dependency>
   <dependentAssembly>
        <!-- Load Common Controls 6 instead of 5 to get WinXP native-
             looking controls in the client area. -->
        <assemblyIdentity type="win32"
             name="Microsoft.Windows.Common-Controls"
             version="6.0.0.0"
             publicKeyToken="6595b64144ccf1df"
             language="*"
             processorArchitecture="x86"/>
   </dependentAssembly>
   </dependency>
</assembly>
屏幕输出太快了,怎么能暂停一下?
Ctrl+S 快捷键可以暂停终端,Ctrl+Q 恢复。
怎么翻页?
Shift+PageUp/PageDown 一页一页的翻,Ctrl+PageUp/PageDown 则是一行一行的。
不是说 PSCP 一次只能传输一个文件么?为什么我发现能传输很多个?
那是因为 PSCP 发现 SFTP 协议可用,优先使用 SFTP 协议来传输文件
为什么执行了 pscp、psftp、plink 这些命令总是说错误的命令呢?
应该把 PuTTY 所在的路径添加到 PATH 环境变量中。你可以编辑 c:\autoexec.bat 这个文件,在最后增加一行,把 c:\path\to\putty 换成你的真实路径
set PATH=c:\path\to\putty;%PATH%
在登录的时候出现 "Proxy error: 407 Proxy authorization require" 的错误提示
这 是因为配置的代理服务器需要认证,而我们没有填写正确的用户名或口令。如果用户名填写的是类似 DOMAIN/username 的形式,可以尝试把 DOMAIN/ 去掉,仅仅填写 username 再试一试,还有一种可能性就是代理服务器禁止我们访问 22 目标端口。
每次开机后我都要先打开 Pagent,然后再添加我的私钥,还要输入私钥密码,太麻烦了,有没有简单一点的办法呢?
很 遗憾,比较轻松的办法就是把 Pagent 和 .ppk 文件关联,然后在开始的启动项里添加一个私钥的快捷方式,这样开机后我们只需要输入一下密码就OK了。如果想把输入密码也省掉,唉唉唉,怎么比我还懒呢? 如果你的私钥密码真的是很长很长,那你还是借助第三方工具吧,建议用 KeePass 吧,KeePass 可以用命令行启动省掉输入密码和选择 keyfile 的麻烦。
我希望下次登录服务器的时候,还是能看到这次登录的界面,也就是说可不可以像 Firefox 那样保存 PuTTY 登录的会话呢?
这个问题很多人都会遇到,比如在进行一个长时间的数据处理,而且还不能放到后台执行。这时是不能关闭 PuTTY 的,万一网络状况不好突然断掉,或者是自己的机器死机必须重启,那我们难道只能眼巴巴的看着就要完成的工作付之东流?
当然这些事情是可以避免的,只不过这个功能是通过 GNU Screen 来实现的。GNU Screen 是一个终端窗口管理器,只不过管理的是终端界面,也就是纯文本的界面,而非图形界面。再稍微专业一些的说法就是:用一个物理终端模拟了多个虚拟终端。
如何安装 GNU Screen 这里就不说了,单说用 PuTTY 如何方便的去使用 GNU Screen。参考一下前面提到的如何自动执行一个命令,在 Remote Command 这个里面填写如下命令:
screen -RD
然 后保存会话,登录。嗯,接下来你会发现什么呢?当然是命令提示符了,然后 ls 一下,一切正常啊,GNU Screen 呢?看到了没?其实我们已经在 Gnu Screen 里面了,在有的系统上,你会看到 PuTTY 的标题已经变成了 screen,有的显示的就是主机名,不管怎样,我们已经运行在 GNU Screen 里面了。如果你发现 PuTTY 是一闪而过,没有登录上去,那估计就是 GNU Screen 没有安装成功。
在 GNU Screen 中的每一个终端窗口都有一个编号,编号从 0 开始,再创建一个终端窗口,编号就是 1 了,以此类推。
下面简述一下 GNU Screen 的最经常使用的快捷键:
  1. 关闭 GNU Screen:Ctrl+a,然后 d,下面就用 C-a d 来表示了。或者 Ctrl+a Ctrl+d,下面就用 C-a C-d 来表示。放心这个只是关闭了窗口,里面的程序还都正常的运行,下次用命令 screen -RD 又都可以看到了。
  2. 再打开一个新的终端窗口:C-a c 或者 C-a C-c
  3. 切换到下一个终端窗口:C-a n 或者 C-a C-n
  4. 切换到前一个终端窗口:C-a p 或者 C-a C-p
  5. 切换到 0 号终端窗口:C-a 0 或者 C-a C-0
  6. 切换到 8 号终端窗口:C-a 8 或者 C-a C-8
  7. 快速切换到上一个打开的终端窗口:C-a C-a。这个需要稍微解释一下,比如现在我们在第 7 号终端窗口,按快捷键 C-a 2 切换到了 2 号终端窗口。要想再回到 7 号终端窗口,一个办法就是 C-a 7,另外一个办法就是 C-a C-a。
  8. 给运行在终端窗口的程序发送 ^a:C-a a,因为 GNU Screen 的所有快捷键都是以 C-a 开始,所以要给程序发送 ^a 就是这个方法了。
  9. 黑屏:C-a -。这个作用就类似屏保了,万一有些程序不方便让别人看到,切换到其他终端窗口也不合适,那就这个了,当然创建一个新的终端窗口也可以。
  10. 滚屏:C-a [ 或者 C-a C-[ 或者 C-a esc。然后用 PageUp/PageDown 就可以翻页了,再次按下 esc 就退出滚屏模式了,这个模式也是 copy 模式,这里就不细说了。
这里只是列出了常用的操作,还有很多强大的操作以及配置,大家 man screen 吧。
from http://chaifeng.com/blog/2007/06/putty_200611.html

 ---------------------------------------------------

基于公钥认证方式的OpenSSH Server的自动登录

 

假设要以用户 rainux 的身份登录运行 OpenSSH Server 的远程主机 www.rainux.org(现在几乎所有的 Linux 服务器都使用 OpenSSH Server 作为 SSH Server),那么需要做的操作如下:
1.生成用于 SSH 身份认证的密钥。密钥由公钥和私钥组成,一个公钥只对应一个私钥,一个私钥也只对应一个公钥。
2.将 OpenSSH 格式的公钥文本追加到远程主机上的 ~rainux/.ssh/authorized_keys 文件里(~rainux 意为用户 rainux 的 HOME 目录)。注意公钥文本中应该没有换行符,一行就是一个公钥。
3.确保 ~rainux/.ssh/authorized_keys 权限为 600,~/rainux/.ssh 目录权限为 700,并且它们的所有者都是 rainux。
4.指定 SSH 客户端使用对应的私钥并以用户 rainux 的身份登录 www.rainux.org,此时无需输入 rainux 在 www.rainux.org 上的密码。
注意:如果私钥是以加密形式存储的(强烈建议使用一个强壮的密码加密私钥,这样即使私钥文件被窃取,也无法被直接使用),第四步仍然需要输入加密私 钥所用的密码。但是 PuTTY 和 OpenSSH 都有提供一个代理程序用于避免多次重复输入密码。运行代理程序后将私钥添加到其中,并且输入一次加密私钥所用的密码,然后保持代理程序的运行,以后 SSH 客户端即可在需要使用私钥进行身份认证的场合请求代理程序去完成身份认证(这是为了确保私钥不会被泄漏到任何使用代理程序的客户端上),无须再次输入任何 密码。

Linux / Cygwin / MSYS 上使用 OpenSSH Client

生成密钥

执行 ssh-keygen 接受默认文件名,并且输入加密私钥用的密码(passphrase)即可生成私钥 ~/.ssh/id_rsa 和对应的公钥 ~/.ssh/id_rsa.pub。其中 id_rsa.pub 的内容可以直接追加到远程主机的 authorized_keys 文件里。

使用私钥

把公钥部署到远程主机上后,即可直接执行 ssh rainux@www.rainux.org 来登录远程主机。但如果私钥是加密形式保存,如上所述应该使用代理程序 ssh-agent 来避免每次输入密码。
直接执行 ssh-add 命令可以添加刚才生成的私钥到 ssh-agent 里,也可以用 ssh-add -l 查看已经添加的私钥。如果执行 ssh-add 时提示无法连接身份认证代理,则需要使用以下命令来启动 ssh-agent。
eval `ssh-agent`
eval `ssh-agent`
使用 eval 是为了执行 ssh-agent 输出的设置环境变量的 bash 命令,以确保 ssh-add 可以通过 SSH_AUTH_SOCK 环境变量找到 ssh-agent。
GNOME 的桌面系统如果有安装 gnome-keyring,它会自动管理 ssh-agent,通常甚至无须手工添加私钥到 ssh-agent 里,第一次使用公钥时 gnome-keyring 就会提示输入一次密码,以后则不再需要。

Windows 上使用 PuTTY

生成密钥

到 PuTTY 的下载页面下载 putty-0.60-installer.exe 或者 putty.zip,两者都包含 PuTTY 所有的组件。
安装好 PuTTY 之后(对于 zip 版本来说,解压到任意目录即可)运行 PuTTYGen 生成自己的密钥。选择密钥类型为 SSH-2 RSA,点击 Generate,按照提示在 PuTTYGen 窗口内随机移动鼠标直到进度条达到 100%,然后 PuTYYGen 会生成密钥并且显示其公钥部分信息。这里可以填写一个有意义的注释,然后输入一个用来加密私钥的强壮的密码(Key passphrase)。最后点击 Save private key 将私钥保存为一个 .ppk 文件。不需要单独 Save public key,因为 .ppk 文件里已经包含了公钥。并且通过 Save public key 保存出来的公钥文件格式与 OpenSSH 的格式并不相同,若要将公钥部署到使用 OpenSSH Server 的服务器上,只能使用 PuTTYGen 窗口上显示的那一段 Public key for pasting into OpenSSH authorized_keys file。

使用私钥

将公钥部署到远程主机上之后,使用 PuTTY 登录该远程主机时可以在 Connection > SSH > Auth 里选择用于身份认证的私钥文件。同样,如果私钥是加密形式保存,应该使用代理程序 Pageant 以避免每次输入密码。
最简单的办法是创建一个 Pageant 的快捷方式,并且将 .ppk 私钥文件作为参数加到快捷方式的“目标”栏里,添加之后看上去应该像这样:
C:\PuTTY\pageant.exe D:\main.ppk "D:\My Secrets\secondary.ppk"
C:\PuTTY\pageant.exe D:\main.ppk "D:\My Secrets\secondary.ppk"
就像上面的例子一样,如果私钥文件路径中带有空格,应该使用引号将其括起来。通过这个快捷方式启动 Pageant 则会自动装载指定的私钥文件,并且立即询问用于加密私钥的密码。以后只要保持 Pageant 的运行,并且在 PuTTY 的某个 Saved session 里设置 Connnection > Data 里设置 Auto-login username,即可实现双击该 session 则完全自动登录。
-----------------------------------------------------------------------------------------------------------------------
搞定公钥/私钥的方式自动登录SSH,免去密码输入之苦。

第一步,生成钥匙对

$ ssh-keygen -d
Generating public/private dsa key pair.
Enter file in which to save the key (/home/fwolf/.ssh/id_dsa): .ssh/fwolf_dsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
open .ssh/fwolf_dsa failed: No such file or directory.
Saving the key failed: .ssh/fwolf_dsa.
这里我使用的是dsa格式的密钥,也可以使用-t rsa参数指定rsa格式,我实在不知道他们有啥差别;不带参数大概是针对ssh1的密钥格式,现在应该很少人用ssh1了。提示输入 passphrase(其实相当于私钥的密码)的时候,回车表示不设密码,在这里我设置了非空的密码。

第二步,把公钥上传到服务器上去

$ ssh-copy-id -i ~/.ssh/fwolf_dsa.pub fwolf.com
30
fwolf@fwolf.com's password:
Now try logging into the machine, with "ssh 'fwolf.com'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.
一个命令搞定,当然此时我们仍然需要服务器ssh的密码,才能把pub key传上去,ssh-copy-id命令会直接把key添加到.ssh/authorized_keys文件中,这和下面的做法效果是一样的:
$ scp ~/.ssh/fwolf_dsa.pub fwolf@fwolf.com
...
$ ssh fwolf@fwolf.com
...
$ cat fwolf_dsa.pub >> ~/ssh/authorized_keys

第三步,我们来享受一下自动登录的乐趣吧

$ ssh fwolf.com。。。疑,怎么还需要输入密码呢?如果你遇到和我一样的问题,并且pub key上传也没有问题的话,说明是ssh客户端配置没有搞定,注意第一步中我更改了key文件的默认名称不是么?所以把/etc/ssh /ssh_config文件拷贝一份存为~/.ssh/config,然后编辑之,更改其中IdentityFile ~/.ssh/id_dsa这一行,去掉注释,添上你实际的dsa私钥文件名就可以了,然后再次ssh:
$ ssh fwolf.com
Enter passphrase for key '/home/fwolf/.ssh/fwolf_dsa':
......(登录成功)

第四步,去掉那该死的passphrase

在上面的第三步中,ssh虽然无须再输入用户密码,但仍然要输入私钥的passphrase,这和输入ssh密码一样麻烦,幸好托ibm的福,大牛Daniel Robbins为我们介绍了使 用ssh-agent和keychain免去输入密码之烦的方法,不过应该不适用于我们这样经常需要开关机的情况,所以,只好回到第一步,生成一 对没有passphrase的密钥来用,虽然安全性下降了些,倒是非常方便。

安全建议

  1. 如果条件允许,使用带有passphrase的密钥,配合ssh-agent和keychain使用。
  2. 如果需要从不同的计算机登录服务器,最好使用不一样的密钥对。
  3. 记得定期更换密钥对,切记。

参考

FROM: http://www.fwolf.com/blog/post/279
------------------------------------------------------------------------------

制作不用密码可立即登入的 ssh 用户

如果在ubuntu下用ssh命令登录主机的话,总是会要求你输入密码,那么有什么法子可以不用密码直接登录呢?
原先我用的是在主机cpanelssh-key manage里,先创建一个key,然后下载private key,放在ubuntu下的~/.ssh目录下,这样即可。
如图:
cpanel ssh
第二种方法就是在ubuntu本地创建key,然后上传到sever上。

  1. 首先,先在 Client 上面创建 Public Key Private Key 这两把钥匙,利用的指令为 ssh-keygen 这个命令;再来,将 Private Key 放在 Client 上面的家目录,亦即 $HOME/.ssh/ , 并且修改权限为仅有该 User 可读的状态;创建key
  2. 最后,将那把 Public Key 放在任何一个您想要用来登录的主机的 Server 端的某 User 的家目录内之 .ssh/ 里面的认证文件即可完成整个程序。上传公钥
  3. 测试一下。输入 ssh test@linux。
注释:test为你的id。test2是你的ubuntu机器名字。linux就是主机服务器地址了。上图中192.168.0.2是主机ip地址,写域名也行。
两种方法都可以,任选一个。如果你喜欢命令行就用第二种方法吧。呵呵。
可具体参考鸟哥的linux私房菜
-----------------------------------------
1. 在本地机器执行
ssh-keygen –t rsa
过程中一路回车。
2.将生成的.ssh/id_rsa.pub文件中的内容复制到目标机的
.ssh/authorized_keys
文件中(若没有则创建)。
3.登陆到目标机器就不需要输入密码了。
from http://vastars.info/linux/ssh-no-passwd.html
------------------------------------------------------------------
howto use pubkey authtication under CentOS.

Ok, let’s continue.
First, we need enable Pubkey Authtication.
vi /etc/ssh/sshd_config
uncomment and modify these lines below:
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no
save file and quit vi. what we did is tell ssh daemon to use PubkeyAuthentication instead of traditional PasswordAuthenrication. avoid middleman attack.
right now restart ssh daemon service.use command below:
service sshd restart
Second, generate our pubkey through this command ssh-keygen. and i think you should have a good habit, when you find an unknown well command, you should use man to understand and know it.
ssh-keygen -t dsa
okay, follow instructions to complete your key generation.
right now we have 2 files under /home/USERNAME/.ssh, named id_dsa and id_dsa.pub. what should we do next? set proper permission and rename id_dsa.pub to authorized_keys.
mv /home/USERNAME/.ssh/id_dsa.pub
/home/USERNAME/.ssh/authorized_keys
chmod 644 /home/USERNAME/.ssh/authorized_keys
chmod 700 /home/USERNAME/.ssh
After that, download your id_dsa for secureCRT by any SFTP clients or scp. Well, right now we have done with Server’s work. Below it’ll show you how to use pubkey to log in your Server.
Open SecureCRT, Click “New Session”, fill with your server’s ip, specified port, your username, click ok to close dialog window. Then, right click the session you created just now, click Properties, and choose SSH2 Category on the left, authentication area, uncheck PasswordAuthentication, single click “PublicKey”, then click “Properties”, “Use Identify or certificate file”, browser your id_dsa downloaded just now, click ok to close dialog.
Well, i think you can connect to your server without any password. Of course, for secure reason, you still need set passphrase and keep your files id_dsa and id_dsa.pub safe. Hypothetically, if you have more then one server, you can use your id_dsa.pub as many as you wish.
----------------------------------------

linux上的图形ssh连接器(带源码)



协议 BSD
环境 python 2.6 + pygtk + pexpect + ssh
ubuntu下标准自带

支持断线重连,
包括ADSL拨号中断后的自动重连
(需要设置设备名,一般默认是ppp0,可用ifconfig查看)
还不支持缩小到托盘,建议放到别的工作区。

使用方法 双击sshclient.py点运行

附件

  sshclient.rar  (3.81 KB)
-----------------------------------------------------------------
什么是SSH?
传统的网络服务程序,如:ftp、pop和telnet在本质上都是不安全的,因为它们在网络上用明文传送口令和数据,别有用心的人非常容易就可以截获这 些口令和数据。而且,这些服务程序的安全验证方式也是有其弱点的,就是很容易受到“中间人”(man-in-the-middle)这种方式的攻击。所谓 “中间人”的攻击方式,就是“中间人”冒充真正的服务器接收你的传给服务器的数据,然后再冒充你把数据传给真正的服务器。服务器和你之间的数据传送被“中 间人”一转手做了手脚之后,就会出现很严重的问题。
SSH的英文全称是Secure SHell。通过使用SSH,你可以把所有传输的数据进行加密,这样“中间人”这种攻击方式就不可能实现了,而且 也能够防止DNS和IP欺骗。还有一个额外的好处就是传输的数据是经过压缩的,所以可以加快传输的速度。SSH有很多功能,它既可以代替telnet,又 可以为ftp、pop、甚至ppp提供一个安全的“通道”。
最初SSH是由芬兰的一家公司开发的。但是因为受版权和加密算法的限制,现在很多人都转而使用OpenSSH。OpenSSH是SSH的替代软件,而且是免费的,可以预计将来会有越来越多的人使用它而不是SSH。
SSH是由客户端和服务端的软件组成的,有两个不兼容的版本分别是:1.x和2.x。用SSH 2.x的客户程序是不能连接到SSH 1.x的服务程序上去的。OpenSSH 2.x同时支持SSH 1.x和2.x。
SSH的安全验证是如何工作的
从客户端来看,SSH提供两种级别的安全验证。
第一种级别(基于口令的安全验证)只要你知道自己帐号和口令,就可以登录到远程主机。所有传输的数据都会被加密,但是不能保证你正在连接的服务器就是你想连接的服务器。可能会有别的服务器在冒充真正的服务器,也就是受到“中间人”这种方式的攻击。
第二种级别(基于密匙的安全验证)需要依靠密匙,也就是你必须为自己创建一对密匙,并把公用密匙放在需要访问的服务器上。如果你要连接到SSH服务 器上,客户端软件就会向服务器发出请求,请求用你的密匙进行安全验证。服务器收到请求之后,先在你在该服务器的家目录下寻找你的公用密匙,然后把它和你发 送过来的公用密匙进行比较。如果两个密匙一致,服务器就用公用密匙加密“质询”(challenge)并把它发送给客户端软件。客户端软件收到“质询”之 后就可以用你的私人密匙解密再把它发送给服务器。
用这种方式,你必须知道自己密匙的口令。但是,与第一种级别相比,第二种级别不需要在网络上传送口令。
第二种级别不仅加密所有传送的数据,而且“中间人”这种攻击方式也是不可能的(因为他没有你的私人密匙)。但是整个登录的过程可能需要10秒。
安装并测试OpenSSH
因为受到美国法律的限制,在很多Linux的发行版中都没有包括OpenSSH。但是,可以从网络上下载并安装OpenSSH(有关OpenSSH的安装 和配置请参考:http://www.linuxaid.com.cn/engineer/brimmer/html/OpenSSH.htm)。
安装完OpenSSH之后,用下面命令测试一下:
ssh -l [your accountname on the remote host] [address of the remote host]
如果OpenSSH工作正常,你会看到下面的提示信息:
The authenticity of host [hostname] can’t be established.
Key fingerprint is 1024 5f:a0:0b:65:d3:82:df:ab:44:62:6d:98:9c:fe:e9:52.
Are you sure you want to continue connecting (yes/no)?
OpenSSH告诉你它不知道这台主机,但是你不用担心这个问题,因为你是第一次登录这台主机。键入“yes”。这将把这台主机的“识别标记”加到“~/.ssh/know_hosts”文件中。第二次访问这台主机的时候就不会再显示这条提示信息了。
然后,SSH提示你输入远程主机上你的帐号的口令。输入完口令之后,就建立了SSH连接,这之后就可以象使用telnet那样使用SSH了。------------------------------------------------------------------------------------------------------------------------

putty-tunnel-manager——Easily open tunnels, from any PuTTY session, from your system tray

PuTTY Tunnel Manager allows you to easily open tunnels, that are defined in a PuTTY session, from the system tray. You can also move the tunnels from PuTTY to PuTTY Tunnel Manager. This allows you to use PuTTY just for SSH shell sessions (without opening tunnels), and use PuTTY Tunnel Manager just for tunneling.

Features

  • Created specifically for tunneling over SSH sessions
  • Open and close sessions from the system tray
  • Works alongside PuTTY and Pageant, using Plink
  • Easily add and remove tunnels from existing PuTTY sessions
  • Can store tunnels outside the regular PuTTY sessions
  • Keep track of open tunnels and prevent multiple tunnels from listening on the same port
  • Reconnects when your PC wakes up from stand-by
  • Simple interface
  • One file, small size, with a cool icon

Screenshots

 

Download and installation

Like PuTTY, this program is just a single executable file. You will need Microsoft’s .NET Framework version 2 or higher to start it but you’ll probably have it already.
  1. Download the latest version from this page and place it in your PuTTY directory, or any other directory.
  2. Download Plink (plink.exe) from here and place it in the same directory.
  3. Start PuTTY Tunnel Manager (ptman.exe).
  4. If you put ptman.exe and plink.exe in the same directory, you’re ready to go. If not, the settings window will show and you should point to plink.exe yourself.
See the Quick guide to get started.
I also recommend to use Pageant for public key authentication (read: no passwords and even more secure). See the Using pageant section for a short explanation.
看起来和Linux上的gSTM差不多,可以用来管理plink.exe来翻墙,不过没有MyEnTunnel方便,自己研究吧!
项目地址:http://code.google.com/p/putty-tunnel-manager/
----------------------------------------------------------------

PuTTY手机端-S60平台实现SSH登录的手机客户端

PuTTY是一款Windows操作系统平台下提供SSH方式接入的强大软件,其实PuTTY还提供了运行在S60及较老的Series 80等Symbian平台上的手机版本,功能同样强悍。可登录http://s2PuTTY.sourceforge.net,选择下载与你手机相适应的版本并安装到手机即可,非常方便,接下来我将以PuTTY S60第3版软件为例详细介绍其使用方法。
PuTTY手机版可以创建和保存多个实例,每个实例都有一个名字,分别对应你的某个网站SSH登录后台,便于多个网站间的管理。第一次使用时可以直 接点 击“Default”实例,在弹出的“Host”一栏中输入支持SSH管理的主机地址或者你网站的网址后确认。稍等片刻,在“Login as”窗口中输入你的后台用户名,之后输入你的管理密码即可正常登录熟悉的SSH后台。此外,你还可以在每个实例的“General”项中直接设置好你的 “Host”及“Username”,其它参数保持默认,以后管理起来更加得心应手。

Putty手机端可以建立多个SSH管理实例   General中可以直接设置主机地址及用户名
由于大部分S60手机都不具有QWERTY全键盘,即使是E61、E90等这些全键盘机型也依旧缺少很多重要的按键如Esc及Tab键等,为了保证 可以输 入一些特殊按键如Ctrl、Alt等,PuTTY S60版还提供了一个Send网格控制界面,该输入界面可以从软件的右软键“Send”或者“Opinion”中的“Send”进入,非常方便。

使用SSH成功登录后的系统欢迎界面     软件的全屏显示模式及Send网格控制界面
PuTTY for Symbian OS和电脑上的PuTTY界面差不多,也可对文件夹进行高亮,可以进入Vi编辑器、具有Tab键的功能、多种显示字体、全屏显示等工具都一应俱全。此外, 使用上下方向导航键还可以选择以前使用过的命令,功能甚为强大。
小提示:在开始使用PuTTY手机版管理你的网站之前,请先确认您手机默认接入点为CMNET或3GNET,而非CMWAP或3GWAP,否则会出现连接不上服务器的情况。
--------------------------------------------------------------
http://docs.google.com/View?id=dgdzk68d_16q7dr2hf3
--------------------------------------------------------------------

在内网里,用putty(plink)一键翻墙

作为一个内网用户,我一直使用SecureCRT来翻墙,SecureCRT的版本不同,连接外网ssh服务器的初始速度还不一样,也许是破解版的原因:D
putty的初始连接速度一直就很快,但是putty不能保存完整的会话帐号密码,每次都要手动输入,很是麻烦,putty胜在小巧,开源,所以一直备用
今天下午把PuTTY User Manual大致看了一遍,也没找到命令行下直接调用代理服务器的命令语句。但是通过load session,半自动解决了。
plink 一行批处理脚本搞定内网翻墙,不用需要图形界面,键入密码之类的操作
plink mysessions -v -N -l username -pw password username@sshhost

mysession即你事先设置好的服务器内容,主要是设好内网代理。
putty-sessions-proxy设置
putty session proxy
.
plink命令行脚本运行成果

from http://blog.wanjie.info/2010/04/puttyplink%E5%86%85%E7%BD%91%E4%B8%80%E9%94%AE%E7%BF%BB%E5%A2%99/
--------------------------------------------------------------------------

内网(公司局域网通过代理上外网)ssh翻墙

内网是指那些通过公司统一的http代理,浏览器上网的情况,这种情况下如何用ssh翻墙呢?
Tunnelier的设置方法:
Tunnelier设置代理很简单(如下图),打开软件后点击Proxy即弹出代理设置界面,勾选Use proxy 选择代理类型(看看公司使用的是http类型还是socks类型的代理)代理服务器地址和端口(如果有密码填写用户名和密码)点击ok就完成了代理设置, 至于ssh服务器设置和以前的 一样.
http://www.dumpt.com/img/files/t7z36ysfi39opyaxkte8_thumb.jpg
注意:有的代理服务器没有开放ssh服务器常用的22端口导致连接失败请更换其他代理服务器继续试(cjb.net等支持使用443端口连接ssh服务器而一般代理服务器都开放了443端口所以使用443端口连接ssh服务器连接成功的可能性更大)
putty设置方法:
putty原版是不能自动保存密码的这样虽然很安全不过对于只用来翻墙的用户来说每次都输入密码很不爽呀,幸好它是开源软件有高人编译了能保存密码的修改版(下载地址:http://sharesend.com/ydaco

------------------
plink、myentunnel和MrZhang的设置方法:

内网用户使用plink、myentunnel和MrZhang连接ssh服务器的方法可以 看http://blog.wanjie.info/2010/04/puttyplink%E5%86%85%E7%BD%91%E4%B8%80%E9%94%AE%E7%BF%BB%E5%A2%99/,(myentunnel和MrZhang只需设置ssh服务器为你事先使用putty设置好的配置的名字例如文中的 mysessions,其他和以前一样。注意要使用putty原版不能使用上文中的修改版,因为putty原版的配置文件存放在注册表里而那个修改版的配置文件保存在一个其创建的文件里)
----------------------------------------------------------------
Corkscrew内网代理环境SSH


一句话介绍,开瓶器是一个隧道通过HTTP代理SSH的工具。Corkscrew is a tool for tunneling SSH through HTTP proxies.

虽然大多数人用不到这种极端环境,内网+代理环境上网+linux环境+需要外部ssh。

当然windows环境下,内网代理,ssh很简单putty或SecureCRT,都有 防火墙选项。可以设置代理。

linux下命令行 ssh,我把ssh help翻了一遍也没找到有设置代理的选项。Google漫天搜索终于找到了Corkscrew:) 试用了一阵,稳定好用,所以记下来。

使用方法简单

1,下载-http://www.agroman.net/corkscrew/corkscrew-2.0.tar.gz

2,安装
tar xzvf corkscrew.tar.gz
cd corkscrew
./configure
make && make install

3, 修改用户目录下的.ssh/config文件,正常情况下没有config文件:)
Host *
  ProxyCommand corkscrew http-proxy.example.com 8080 %h %p
4, 搞定收工。
ssh somewhere.com 试试吧。
如果需要更详细的介绍,参阅http://www.mtu.net/~engstrom/ssh-proxy.php
from http://blog.wanjie.info/2010/03/corkscrew-ssh-over-http-proxy/
由于笔者在公司通过内网HTTP代理方式上网。貌似代理无法直接在ssh上使用。笔者在查阅资料后发现。ssh需要经过tunnel(隧道)来使用HTTP代理(或者还有其他好方法?笔者还不知道=_=!,各位网友不吝赐教)。
1、下载一个tunnel软件,如 corkscrew 下载地址 解压后,编译
tar zxf corkscrew-2.0.tar.gz
cd corkscrew-2.0
./configure
make && make install
2、修改ssh配置
vi /etc/ssh/ssh_config
添加
Host *
ProxyCommand corkscrew server port %h %p
保存后,可以直接使用ssh登录了
------------------------------------------------------------------
PUTTY默认不支持记住密码,修改版的还是不要用,好在SSH支持证书登陆,我也问了生产环境下的朋友,他们登陆SSH也是用证书.
这里介绍的不是双Linux环境下的SSH证书登陆,而是Windows下用Putty证书登陆至你的Linux服务器/VPS.
目前我用的是Putty中文版,来自GoogleCode的项目:http://code.google.com/p/puttycn/
1.用PuTTY SSH 密钥生成工具puttygen.exe生成密钥.
生成的密钥类型和位数按照默认的就OK,SSH-2 RSA,1024位
生成密钥时你需要在空白区域移动鼠标,以便产生随机数据
点击保存私钥(可以不设置密码保护),不要生成公钥,因为PUTTY生成的公钥OpenSSH无法使用.
2.SSH密码方式登入远端Linux服务器/VPS,创建.ssh/authorized_keys.
vim ~/.ssh/authorized_keys
将puttygen.exe生成的公钥内容粘贴至~/.ssh/authorized_keys.
注:公钥内容就在显示的公钥(P)由OpenSSH认可: 这行字符下面.
至于为什么文件名是authorized_keys,可以在/etc/ssh/sshd_config中找到下面两行
#PubkeyAuthentication yes
#AuthorizedKeysFile .ssh/authorized_keys
3.用SSH证书登陆你的Linux服务器/VPS
Putty→会话:将服务器IP填好
Putty→连接→数据:填好自动登陆用户名
Putty→连接→SSH→认证:选择认证私钥文件
回到Putty→会话:保存的会话,填个名称保存下吧,下次直接双击名称就可以登录了,赶紧登录吧.
4.为了安全你需要取消SSH的密码认证方式.
vim /etc/ssh/sshd_config
添加下面这行
PasswordAuthentication no 
重启SSH服务
service sshd restart
不过注意保存好你的私钥文件哦.
from http://www.shocr.com/sshcertificate-putty-linux/
------------------------------------------------------

通过ssh证书让putty自动登录

其实可以ssh证书的方式让putty安全、方便的实现自动登录。
step0. 所需软件

putty.exe, puttygen.exe(官方)
step1. 生成密钥
运行puttygen.exe,按照默认即可:选择SSH-2 RSA1024位的key、空白的Key passphrase,然后点击Generate,在空白区域不断随机挪动光标,直到它产生key。将它生成的那一行Public key粘贴到文件里,比如叫id_rsa2.pub;然后点击"Save private key",将对应的密钥保存下来,如id_rsa2.prv。
注意:不要直接使用点Save public key按钮后保存的文件,它的格式在后面没法用.
step2. 配置远程帐户
登录远程帐户,将Public key即id_rsa2.pub里的内容添加到相应的文件里:
mkdir ~/.ssh
cat > ~/.ssh/authorized_keys
(此时粘贴内容,然后在新行里按Ctrl + D结束)
同时应该确保~/.ssh目录的权限是700。
step3. 配置Putty
进行基本设置之后,在Connection / Data分类的Auto-login username里填写你远程的用户名;然后在下面的SSH / Auth分类的Private key file for authentication里选择刚才保存的密钥文件id_rsa2.prv。
然后保存设置,登录即可。
注意事项:
- 生成的文件,尤其是私有文件id_rsa2.prv, 应严加防范妥善保存
- 通过ssh-keygen命令生成的key没法在putty里直接使用,需要经过puttygen.exe转换
- ssh-keygen的使用方法请参考《基于SSH密钥对的自动登录
参考资料:
from http://smzz.org/node/37
------------------------------------------------
Scott Merrill writes in to say:
I noticed recently that ssh connections from my Ubuntu laptop to my
Debian server would time out and disconnect if I left the connection
idle for a long-ish period of time. This really annoyed me, because my
Debian desktop does not exhibit this behavior when connecting to the server.
I added the following line to /etc/ssh/ssh_config :
ServerAliveInterval 5
That seems to have fixed the problem, and my laptop can now remain
connected, though idle, to my server. Maybe this will help someone
else, too.
What this does, essentially is every 5 seconds, the client sends a small keep-alive packet to the server to make it look like the ssh connection is being actively used. The reason for Scott’s timeout could be a NAT firewall that seeks to minimize the nember of active connections to reduce its memory footprint, or to improve performance for other clients. Most firewalls and networks let you keep your connections alive for as long as you wish, but some may act up, and that’s when you can use Scott’s trick.
Tip: Change 5 to 240 or 300, so that instead of every 5 seconds, the keep-alive signal is sent only once in 4 or 5 minutes.
-------------------------------------------------------------------------------

SSH Tunnel之fuck GFW整体解决方案

在不能使用代理服务器或者tor绕开防火长城的场合(比如单位里面不可以使用非企业代理,比如日后tor被土共封锁),如果ssh 22端口没有被封锁,那就可以利用OpenSSH强大的tunnel功能来
实现高速安全的访问Internet任意开放网站的任意开放端口 。在这里简称挖地道

1准备条件:
1.1 某国外主机shell,这个需要你自己去找,买一个或找找一个免费的,需要上面的开启sshd
1.2 Firefox浏览器配合foxyproxy扩展,虽然用IE也方便,但是当大多数网站不需要挖地道访问只有个别网站需要挖地道访问自己又是懒人懒得每次访问blocked网站去切换浏览器的代理设置的情况下,用foxyproxy这个基于模版自动匹配代理的扩展还是很方便的。
1.3 国外代理服务器,任意一个高速匿名免费代理服务器

2原理:
2.1首先man ssh,注意ssh的manpage里面这也一个选项:

-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 for-
ward privileged ports. IPv6 addresses can be specified with an
alternative syntax: port/host/hostport

2.2基本格式

ssh -l USER -L local_port:any_host_blocked_by_gfw:the_blocked_hosts_port ssh host_which_out_of_gfw

这样任何被屏蔽的主机(any_host_blocked_by_gfw)的任何端口(the_blocked_hosts_port),就可以在本机127.0.0.1的localport访问了

2.3解释,这里有好几个host不要搞错。
ssh -l USER是你用来登录目标ssh主机的用户名,ssh就加上一个-l选项
local_port:本机的某端口,最好大一些,保证没有被其他程序占用的,以后被屏蔽主机的某端口就被映射在本机的此端口
any_host_blocked_by_gfw:任何一个被gfw干了的主机,比如zh.wikipedia.org
the_blocked_hosts_port:前面提到的被干了的这个主机的某个端口,比如25 23 80
host_which_out_of_gfw:任何一台不在土共的GFW范围内的ssh host

2.4例子:
ssh -l fuckGFW 8088:zh.wikipedia.org:80 fuckgfw.free.com

我用fuckGFW帐号登录fuckgfw.free.com主机,并且把维基百科中文的80端口映射到本机的8088端口,这样下次用http://localhost:8088来访问维基百科

3应用:
每 次去挖这样一个坑麻烦了点,这时候就要动动脑筋想想别的办法了。普通的代理服务访问国外主机虽然会被土共的gfw盾,但是,如果把普通国外代理服务器加上 一个ssh的套套,那土共的GFW就煞笔了,而且即使土共把这个代理服务器本身干了也没用,因为我们的国外ssh host和国外的代理服务器都是在GFW之外的,那就是终极解决方案:
用ssh tunnel给国外代理服务器加套
例子:
ssh -l fuckGFW 3128:proxy.anywhere.com:8080 fuckgfw.free.com

按照提示输入fuckGFW帐号在fuckfw.free.com主机的密码,然后保持这个ssh连接不要关掉,
这样就给国外的代理服务器proxy.anywhere.com加了套,然后在本地的浏览器设置代理为localhost:3128,那么只要你到fuckgfw.free.com的连接是22端口的ssh加密连接,土共就对你的内容无可奈何。
至于fuckgfw.free.com和proxy.anywhere.com之间是不是加密的会不会监听,目前看来似乎是不加密的(否则我在防火墙内我的本机开一个ssh再加上一个squid就可以访问任意国外主机了),所有这样做还是有风 险,千万不要用这样的方案访问你的paypal帐号gmail等等。但是用来绕开防火墙,正常使用google是足够了,访问blogspot wikipedia等等也没有问题。
此方案的突出几个优点:
a:不需要在ssh主机上面安装软件,这样需要相对较少的ssh shell权限,很多免费的国外ssh主机就可以达到这个要求。
b:不需要在ssh主机上面开允许连入的端口,这样也可以减少对ssh 主机的需求,很多ssh主机只允许22端口连入时,我们这个方法也可以奏效,以上面的例子,3128端口是开设在你自己使用的client 机器的,8080端口是开设在代理服务器proxy.anywhere.com的,ssh主机上面并没有开设额外的端口,还是只有一个22端口。当 然,ssh主机应该可以访问intenet的任何端口,这个应该不是问题的吧。
c:安全。开设在client的端口默认是只允许client本机访问的,同一局域网无法访问,除非你调整ssh client的设置。而且前面提到的,主机上面除了原先的22端口也不开设任何额外的端口,非常的安全。也避免了自己秘密安装的防火墙被其他人透露后带来流量激增的问题
d:专门针对GFW的关键字过滤,这个方法同其他的绕开GFW主机方案比如在你购买的国外主机安装Phpproxy等 等最大的不同和优点在于此。防火墙最难对付的地方并不是直接block主机地址,而是当访问国外主机返回的字符中有所谓敏感字词的时候给你来个链接重置, 非常的讨厌。用普通的代理服务器(无论是国外的还是你自己安装的还是pkblogs.com等等这种类型的) 可以轻松的绕开GFW对block主机地址的屏蔽,但是当有敏感字词的时候还是难逃法眼。而这个方法,由于从你的client到ssh host之间是ssh密文传播的,GFW无能为力。

4.To Do
通常网上容易找到的代理服务器都是只支持http的,支持https的还没有找到,所以访问https的内容比如 gmail还是没有好的解决方法,目前只能设置一下foxyproxy直接访问https的内容(或者用tor),还有一个办法就是再挖一个通道,把 gmail的pop服务器的端口和smtp直接映射在本地的某端口,宁可暂时放弃一下gmail web的丰富feature,也要不受限制的访问google的服务。注意,在ssh到一台主机的时候,可以同时挖n条隧道的,也就是可以在ssh命令后 面加上n个-L 参数

5.补充
使用windows操作系统的也可以用此方法,putty对ssh的tunnel有完美的支持。

抓 图一张作为例子,第一行是我自己用的http代理,马赛克一下,hoho,第二行和第三行把gmail的pop.google.com和 smtp.google.com的端口加了ssh的套套分别映射到了本机的995和587端口,下面正在填写的那个是一个例子,把国外代理服务器的 anyproxy.abroad.com的8080端口加ssh套套映射到本地的5088端口,供浏览器作为代理服务器 localhost:5088使用。

putty
FROM http://yesure.blogspot.com/2006/11/ssh-tunnelfuck-gfw.html
-----------------------------------------------------------------

from http://www.brandonhutchinson.com/ssh_tunnelling.html

ssh tunnelling

ssh tunnelling is an excellent way to tunnel insecure protocols through a secure communication channel. In this example, I'll tunnel POP3 traffic using ssh. Traditional POP3 traffic, including username and password information, travels clear-text across the network.
OpenSSH is used in the following examples.
To tunnel POP3 traffic using ssh: 1. Make sure an ssh client is installed on your machine and an ssh server is installed on the POP3 server. 2. Create a local ssh tunnel on your machine (port 1234 for this example) to the POP3 server's port 110. You will need to be the root user to bind to "privileged" ports (< 1024). # ssh -f -N -L 1234:localhost:110 user@POP3_server 3. Test the tunnel.  $ telnet localhost 1234 You should see the POP3 server's banner information. 4. Configure your mail client to access your mail via POP3 using mail server localhost and port 1234.

"Reverse" ssh tunnel

It is possible to create a "reverse" ssh tunnel. The reverse tunnel will allow you to create an ssh tunnel from your work computer to your home computer, for example, and then login to your work machine from your home machine even if your work firewall does not permit ssh traffic initiated from your home machine! For this to work, an ssh server must be installed on your work and home computer, and ssh (TCP port 22) must be allowed outbound from your work computer to your home computer. $ ssh -R remote_port:localhost:22 your_home_computer ex. $ ssh -R 2048:localhost:22 home.computer.com At home, you would then run ssh -p 2048 localhost to log into your work computer via ssh. Here is a script I run every 5 minutes through the cron facility on my work system to make sure the reverse ssh tunnel to my home system is up and running. It is useful in case my_home_system is rebooted. 2006-11-15 update:  #!/bin/sh  # $REMOTE_HOST is the name of the remote system  REMOTE_HOST=my.home.system  # $REMOTE_PORT is the remote port number that will be used to tunnel  # back to this system  REMOTE_PORT=5000  # $COMMAND is the command used to create the reverse ssh tunnel  COMMAND="ssh -N -R $REMOTE_PORT:localhost:22 $REMOTE_HOST"  # Is the tunnel up? Perform two tests:  # 1. Check for relevant process ($COMMAND)  pgrep -f -x "$COMMAND" || $COMMAND  # 2. Test tunnel by looking at "netstat" output on $REMOTE_HOST  ssh $REMOTE_HOST netstat -an | egrep "tcp.*:$REMOTE_PORT.*LISTEN" \  > /dev/null 2>&1  if [ $? -ne 0 ] ; then  pkill -f -x "$COMMAND"  $COMMAND  fi 2006-09-20 update using pgrep:  #!/bin/sh  # REMOTE_HOST is the name of the remote system  REMOTE_HOST=my.home.system  # $COMMAND is the command used to create the reverse ssh tunnel  COMMAND="ssh -N -R 7437:localhost:22 $REMOTE_HOST"  # Is the tunnel up?pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND Old script:  #!/bin/sh  # $COMMAND is the command used to create the reverse ssh tunnelCOMMAND='ssh -N -R 31337:localhost:22 my_home_system'  # Is the tunnel up?  CHECK_TUNNEL=`ps -eo args | grep "$COMMAND" | grep -v grep`  # If the tunnel is not up, create the tunnel  if [ -z "$CHECK_TUNNEL" ] ; then  $COMMAND  fi Links:  http://www.akadia.com/services/ssh_port_forwarding.htmlhttp://www.hackorama.com/pages/stunnell.shtml  http://proxytunnel.sourceforge.net/  http://proxytunnel.sourceforge.net/papers/muppet-200204.htmlBack to brandonhutchinson.com.
----------------------------------------------------

http://xn.lupaworld.com/index.php/10/action_viewspace_itemid_33.html

ssh 使用新法

ssh 使用新法:公网(合法 ip)用户访问内网(私有 ip)服务器(http,ftp,sshd,cvs...),内网的朋友不妨一看。
内网的朋友苦于没有合法 ip,不能对外提供 internet 服务。解决方案很多,可以通过在网关做端口映射,或其他的辅助软件等。 本文介绍两种比较简单实用的方法,利用 ssh 这个强大的工具。 (以下方法不分平台,都适用) 案例一、 内网主机 A ,开了 http,ftp ,http ,vnc,sshd,socks5,cvs 等服务。无合法 ip 地址。 外网主机 B ,开了 sshd 服务。有合法 ip : 218.xxx.xxx.xxx 我们的目的是让 B 能访问 A 上的各种服务。 步骤: 1、A 知道 B ip 后,先用 ssh client 连上 B,命令如下: ssh -R 1234:localhost:21 -l root 218.xxx.xxx.xxx 解释: 关于 ssh 的参数,请看 ssh --help -L listen-port:host:port Forward local port to remote address -R listen-port:host:port Forward remote port to local address -L local (本地) -R :remote (远程) -R 1234:localhost:21 其实做了个“端口转发(forward)"。 意思是主机 A 把本地的 21端口(对应ftp服务)映射为 B 的1234 端口(任意未被占用),同时 A 监听 B 的1234 端口。 在 B 上用 netstat -al | grep 1234 ,你能看到这个监听连接。 任何发送到 B 1234 端口的请求将被传送到 A的 21 端口。 2、B 用 ftp 工具(任意,如gftp) 连本地的 1234 端口,输入 A 的 ftp 用户和密码。 ftp localhost 1234 千万不要觉的奇怪,为什么连的是本地的地址。 举个不恰当例子,相当于 A 在 B 的房间里装了个窃听器(监听端口),那么 B 在房间里说的话就通过窃听器传送到了 A。 3、推广: 如果 B 没占用 21 端口的话,那么可以写成: A使用: ssh -R 21:localhost:21 -l root 218.xxx.xxx.xxx B使用: ftp localhost 如果你想使用 A 上的 http 或其他服务,只需改变服务端口: http服务 : A使用:ssh -R 1234:localhost:80 -l root 218.xxx.xxx.xxx B使用:w3m http://localhost:1234 sshd服务: A使用:ssh -R 1234:localhost:22 -l root 218.xxx.xxx.xxx B使用:ssh localhost -p 1234 vnc 服务: A使用:ssh -R 1234:localhost:5901(其他) -l root 218.xxx.xxx.xxx B使用:vncviewer localhost:1 socks5服务: A使用:ssh -R 1234:localhost:1080 -l root 218.xxx.xxx.xxx B 略 cvs 服务: A使用:ssh -R 1234:localhost:2401 -l root 218.xxx.xxx.xxx B使用:cvs -d :pserver:root@localhost:1234/home/cvsroot login 这里是否一定要用 root ,涉及到权限问题,具体还得靠大家来总结经验。 案例二、 部分朋友会问了,这样的话只是两台机器的互相通讯,如何让广域网的人都能访问呢? 聪明的你,这时候可能已经有了答案。 内网主机 A ,开了 http,ftp ,http ,vnc,sshd,socks5,cvs等服务。无合法 ip 地址。 外网主机 B ,开了 sshd 服务。有合法 ip : 218.xxx.xxx.xxx 我们的目的是让 internet 上的任何主机能访问 A 上的各种服务。 步骤: 1、首先,B 的sshd 服务端做点小小的设置: vi /etc/ssh/sshd.config 加入 GatewayPorts yes 然后重启 sshd 服务: /etc /init.d/ssh restart 或 /etc/init.d/sshd restart (解释: 不加,默认会把监听端口绑定在 localhost 或 lo(127.0.0.1),这样除了 B自身别人是没法访问监听端口的。 加入 GatewayPorts yes,把监听端口绑定到 0.0.0.0 ,这样外部的所有机器都能访问到这个监听端口。 主要是考虑安全性问题,默认情况,只允许本地访问。 这里才是真正的难点,实验了一个晚上,累人呀!给点鼓励吧 :) 2、A 知道 B ip 后,先用 ssh client 连上 B,命令如下: ssh -R 21:localhost:21 -l root 218.xxx.xxx.xxx (事先确定 B 的21 端口未被占用) 3、分布在 internet 的其它客户机使用 ftp 工具(任意),连 B 21端口。 ftp 218.xxx.xxx.xxx 21 你会发现自己连上了内网 A 的ftp 服务。 此法和案例一完全一样。 internet --------->> B 21 端口----------->>A 21端口 可以叫做端口转发,或隧道技术,也可以称之为跳板(B),或反弹 。呵呵,我瞎说的。。。 可能遇到的问题: Country:/etc# ssh localhost -p 1234 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that the RSA host key has just been changed. The fingerprint for the RSA key sent by the remote host is be:5f:d2:45:66:4d:0c:9e:2b:6b:45:65:a7:b2:85:28. Please contact your system administrator. Add correct host key in /root/.ssh/known_hosts to get rid of this message. Offending key in /root/.ssh/known_hosts:11 RSA host key for localhost has changed and you have requested strict checking. Host key verification failed. Country:/etc# ssh localhost -p 1234 root@localhost's password: Last login: Mon May 5 02:39:53 2003 from localhost localhost root # 如上问题,请删除 ~/.ssh/known_hosts,然后再试。 点评: 当然 ssh 还有很多的功能没有用,如先用 ssh 连接 上去后,可以用 scp命令来存取文件,等等。 scp -P xxx user@host:path/file 其它突破网关传送文件的方式也千变万化。 优点是: 可以突破网关,一般情况下,向网管要求在网关上给你做端口映射是不现实的,但用此法你可以让要好的朋友给你做。 使用方案一:比较点对点传送文件比较方便,或使用ssh进行远程控制内网。 ssh本身是加密,保证安全可靠。 缺点也不少: 使用 ssh 加密,势必影响性能,可以用 -C 选项调节压缩率。 如果象方案二使用额外的服务器,数据都要服务器中转(我是这样认为,没跟踪过),势必影响速度。 公网的服务器不好找。 建议:恳请编程高手们根据类似得原理,做个端口转发小工具,效果会更好。
-----------------------------------

ssh -R -L -D

一.本地端口转发
A机: 172.16.32.123
B机: 172.16.32.102, 10.0.0.2
C机: 10.0.0.1
(说明:C机与B机直连,C机无网关设置,只能与B机进行通信)
B机:(可以使用netstat -nap |grep 7001看到B机上启动了一个监听7001端口的服务)
luther@gliethttp:~$ ssh -CfNg -L 7001:localhost:22 luther@10.0.0.1
A机:(连接B机上的7001端口,因为B机将7001端口监听到的数据,直接转发给了C机,所以A将成功登录到C机)
luther@gliethttp:~$ ssh -p 7001 luther@172.16.32.102
     这样A机就一下子连接到ip地址为10.0.0.1的C机了,实现了连接穿透.
让我们来仔细理解理解,A和C之间因不位于同一网段而不可见,B和A可见,B和C可见,
于是B就可以担当起转发A数据到C的角色.
连接图:A <=> B <==> C
ssh -L <local port>:<remote host>:<remote port> <SSH地址>
我们再来拆解一下语句:
1. B和C建立ssh连接
ssh luther@10.0.0.1
2. 参数-CfNg -L的解释
C – 压缩数据传输
f – 后台用户验证,允许没有shell的不可登陆账号使用
N – 不执行脚本或命令
g – 允许远程主机连接转发端口
L – 本地转发
3. 7001
表示ssh语句执行时,会同时在B机上由ssh命令自动开启一个监听B机上7001端口的service服务
4. :localhost:22
   这个是最不易搞懂的地方,关键是这个参数是由谁来使用,当B机执行ssh的时候,C机上的ssh server
   会接受B机的ssh连接,同时B机的参数:localhost:22被传递到C机的ssh server行,ssh server会解析
   这个参数,C机上的ssh server会将B机ssh发送过来的数据,转发到<remote host>的<remote port>端口上.
可以使用如下实例验证:
a机: 172.16.32.102
b机: 172.16.32.123
c机: 172.16.32.112
d机: 172.16.32.54
只需要在b机上运行
luther@gliethttp:~$ ssh -CfNg -L 7001:172.16.32.112:22 luther@172.16.32.102
然后在d机上运行
luther@gliethttp:~$ ssh -p 7001 172.16.32.123
数据流图:
d <=> b <=> a <=> c
d机连接b机7001端口,b机将d机发送的数据转发到a机的ssh server上,a机的ssh server根据
参数<remote host>:<remote port>即:172.16.32.112:22的定义,
将接收的数据进一步转发到<remote host>的<remote port>端口上,也就是172.16.32.112的22端口上,
所以d机最终和c机建立了ssh连接[luther.gliethttp]
二.远端端口转发
另一种ssh端口转发方式是使用参数-R,而不是-L.
ssh -R <local port>:<remote host>:<remote port> <SSH地址>
A机: 172.16.32.123
B机: 172.16.32.102, 10.0.0.2
C机: 10.0.0.1
(说明:C机与B机直连,C机无网关设置,只能与B机进行通信)
B机:运行如下命令
luther@gliethttp:~$ ssh -CfNg -R 7001:localhost:22 luther@10.0.0.1
C机:查看由C机上ssh server根据B机ssh连接的参数-R 7001创建的监听端口7001
     我们在C机上使用netstat -nap |grep 7001看到C机上启动了一个监听7001端口的服务,
     而C机上这个监听7001端口的服务是C机的ssh server根据B机执行ssh连接时的
     参数-R 7001而由C机ssh server被动建立起来的.
同时C机上只能使用如下命令和C机自己身上的7001端口建立连接,不能使用ip地址,包括(10.0.0.1)
luther@gliethttp:~$ ssh -p 7001 luther@localhost
或者
luther@gliethttp:~$ ssh -p 7001 luther@127.0.0.1
以上2条命令使得C机可以ssh到B机.
另外也可以和上面-L一样,
B机:运行如下命令
luther@gliethttp:~$ ssh -CfNg -R 7001:172.16.32.123:22 luther@10.0.0.1
这时B机建立与C机的ssh,同时通知C机的ssh server,在C机上开启一个监听端口7001,
这样C机向C机本地的7001端口发送数据的时候,B机就能接收到,然后B机将根据
参数:172.16.32.123:22信息,将C机发送过来的数据转发到A机172.16.32.123的22端口
于是C机执行
ssh -p 7001 luther@localhost
就是等于向A机172.16.32.123的22端口发出ssh连接[luther.gliethttp]
三.比较本地端口转发-L和远端端口转发-R:
ssh -L <local port>:<remote host>:<remote port> <SSH地址>
ssh -R <local port>:<remote host>:<remote port> <SSH地址>
参数-L就是<local port>监听端口在执行ssh的机器上建立,参数<remote host>:<remote port>由<SSH地址>主机处理
参数-R就是<local port>监听端口在<SSH地址>主机上建立,参数<remote host>:<remote port>由执行ssh的机器处理
四.动态端口转发-D,设置SOCKS4和SOCKS5代理功能
B机: 172.16.32.102, 10.0.0.2
C机: 10.0.0.1
在C机上执行
ssh -CfNg -D 7001 luther@10.0.0.2
这样C机上将建立一个7001监听端口,C机可以向7001端口发送任何数据,然后B机10.0.0.2会将C机发送的数据
根据C机发送数据的端口号,动态的向外部递交,一般用在SOCKS代理,
C机的localhost:7001就是代理参数,可以在firefox上设置,这样C机就能通过B机上web网了.
到这里我们可以看出-L就是-D的一个具体实例使用,但是-D不能像-L一样,与指定的端口建立连接,所以-D使用在
SOCKS代理上[luther.gliethttp].
Firefox==>Edit==>Preferences==>Advanced
==>Network/Settings==>Manual proxy configuration
==>SOCKS Host: localhost
==>SOCKS Port: 7001
这样C机就能使用firefox上网了[luther.gliethttp]
(注意:因为C机的网关和DNS都没有设置,所以只能使用firefox中直接输入ip的方式上网,
比如www.google.com的ip地址为64.233.189.103).
五.X协议转发,实现ssh直接打开<SSH地址>主机上的GUI程序
A机(redhat): 172.16.32.102
B机(ubuntu): 172.16.32.123
首先A机进入桌面环境,打开一个terminal,
输入
luther@gliethttp:~$ ssh -X root@172.16.32.123              注意-X大写使能X11转发,           -x小写禁用X11转发
但是缺点是只能查看,不能拖动拷贝到本机
[root@localhost ~]# firefox         执行远程机172.16.32.123上的firefox程序
[root@localhost ~]# nautilus /      执行远程机172.16.32.123上的nautilus文件浏览器
总结:
A机公司局域网
B机公网linux主机
C机家里的notebook
A机:
luther@gliethttp:~$ ssh -CfNg -R 7001:localhost:22     用户名@B机
C机:
luther@gliethttp:~$ ssh -CfNg -L 7000:localhost:7001   用户名@B机
C机:
luther@gliethttp:~$ ssh -p 7000 A机用户名@localhost    就可以登录公司的A机了
C机:
luther@gliethttp:~$ ssh -X -p 7000 A机用户名@localhost 就可以执行A机上的图形程序了,比如nautilus.
-----------------------------------------

ssh可以做端口转发,那么linux说不定也可以,于是在网上随便一找,果然支持 tcp_forward啊,执行下面的内容:
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -p tcp --dport 8388 -j DNAT --to-destination US_VPS_IP:8388

iptables -t nat -A POSTROUTING -p tcp -d US_VPS_IP --dport 8388 -j SNAT --to-source JAPAN_VPS_IP
-------


实战ssh端口转发

读者可以从中了解到如何应用 SSH 端口转发机制来解决日常工作 / 生活中的一些问题。学会在非安全环境下使用端口转发来加密网络应用,保护个人隐私以及重要商业信息。同时也能够用此技术解决工作中一些常见问题,例如解决 防火墙及网络应用本身带来的一些限制。
如果没有ssh服务器,可以使用网络通内网穿透工具,无需设置路由器,无需外网ip,穿透映射内网服务器,网站.

第一部分 概述

当你在咖啡馆享受免费 WiFi 的时候,有没有想到可能有人正在窃取你的密码及隐私信息?当你发现实验室的防火墙阻止了你的网络应用端口,是不是有苦难言?来看看 SSH 的端口转发功能能给我们带来什么好处吧!

端口转发概述

让 我们先来了解一下端口转发的概念吧。我们知道,SSH 会自动加密和解密所有 SSH 客户端与服务端之间的网络数据。但是,SSH 还同时提供了一个非常有用的功能,这就是端口转发。它能够将其他 TCP 端口的网络数据通过 SSH 链接来转发,并且自动提供了相应的加密及解密服务。这一过程有时也被叫做“隧道”(tunneling),这是因为 SSH 为其他 TCP 链接提供了一个安全的通道来进行传输而得名。例如,Telnet,SMTP,LDAP 这些 TCP 应用均能够从中得益,避免了用户名,密码以及隐私信息的明文传输。而与此同时,如果您工作环境中的防火墙限制了一些网络端口的使用,但是允许 SSH 的连接,那么也是能够通过将 TCP 端口转发来使用 SSH 进行通讯。总的来说 SSH 端口转发能够提供两大功能:
  1. 加密 SSH Client 端至 SSH Server 端之间的通讯数据。
  2. 突破防火墙的限制完成一些之前无法建立的 TCP 连接。
图 1. SSH 端口转发
SSH 端口转发
如上图所示,使用了端口转发之后,TCP 端口 A 与 B 之间现在并不直接通讯,而是转发到了 SSH 客户端及服务端来通讯,从而自动实现了数据加密并同时绕过了防火墙的限制。

第二部分 本地转发与远程转发

本地转发实例分析

我 们先来看第一个例子,在实验室里有一台 LDAP 服务器(LdapServerHost),但是限制了只有本机上部署的应用才能直接连接此 LDAP 服务器。如果我们由于调试或者测试的需要想临时从远程机器(LdapClientHost)直接连接到这个 LDAP 服务器 , 有什么方法能够实现呢?
答案无疑是本地端口转发了,它的命令格式是:
ssh -L <local port>:<remote host>:<remote port> <SSH hostname>
在 LdapClientHost 上执行如下命令即可建立一个 SSH 的本地端口转发,例如:
$ ssh -L 7001:localhost:389 LdapServerHost
图 2. 本地端口转发
本地端口转发
这里需要注意的是本例中我们选择了 7001 端口作为本地的监听端口,在选择端口号时要注意非管理员帐号是无权绑定 1-1023 端口的,所以一般是选用一个 1024-65535 之间的并且尚未使用的端口号即可。
然后我们可以将远程机器(LdapClientHost)上的应用直接配置到本机的 7001 端口上(而不是 LDAP 服务器的 389 端口上)。之后的数据流将会是下面这个样子:
  • 我们在 LdapClientHost 上的应用将数据发送到本机的 7001 端口上,
  • 而本机的 SSH Client 会将 7001 端口收到的数据加密并转发到 LdapServertHost 的 SSH Server 上。
  • SSH Server 会解密收到的数据并将之转发到监听的 LDAP 389 端口上,
  • 最后再将从 LDAP 返回的数据原路返回以完成整个流程。
我们可以看到,这整个流程应用并没有直接连接 LDAP 服务器,而是连接到了本地的一个监听端口,但是 SSH 端口转发完成了剩下的所有事情,加密,转发,解密,通讯。
这里有几个地方需要注意:
  1. SSH 端口转发是通过 SSH 连接建立起来的,我们必须保持这个 SSH 连接以使端口转发保持生效。一旦关闭了此连接,相应的端口转发也会随之关闭。
  2. 我们只能在建立 SSH 连接的同时创建端口转发,而不能给一个已经存在的 SSH 连接增加端口转发。
  3. 你 可能会疑惑上面命令中的 <remote host> 为什么用 localhost,它指向的是哪台机器呢?在本例中,它指向 LdapServertHost 。我们为什么用 localhost 而不是 IP 地址或者主机名呢?其实这个取决于我们之前是如何限制 LDAP 只有本机才能访问。如果只允许 lookback 接口访问的话,那么自然就只有 localhost 或者 IP 为 127.0.0.1 才能访问了,而不能用真实 IP 或者主机名。
  4. 命令中的 <remote host> 和 <SSH hostname> 必须是同一台机器么?其实是不一定的,它们可以是两台不同的机器。我们在后面的例子里会详细阐述这点。
  5. 好 了,我们已经在 LdapClientHost 建立了端口转发,那么这个端口转发可以被其他机器使用么?比如能否新增加一台 LdapClientHost2 来直接连接 LdapClientHost 的 7001 端口?答案是不行的,在主流 SSH 实现中,本地端口转发绑定的是 lookback 接口,这意味着只有 localhost 或者 127.0.0.1 才能使用本机的端口转发 , 其他机器发起的连接只会得到“ connection refused. ”。好在 SSH 同时提供了 GatewayPorts 关键字,我们可以通过指定它与其他机器共享这个本地端口转发。
    ssh -g -L <local port>:<remote host>:<remote port> <SSH hostname>

远程转发实例分析

我们来看第二个例子,这次假设由于网络或防火墙的原因我们不能用 SSH 直接从 LdapClientHost 连接到 LDAP 服务器(LdapServertHost),但是反向连接却是被允许的。那此时我们的选择自然就是远程端口转发了。
它的命令格式是:
ssh -R <local port>:<remote host>:<remote port> <SSH hostname>
例如在 LDAP 服务器(LdapServertHost)端执行如下命令:
$ ssh -R 7001:localhost:389 LdapClientHost
图 3. 远程端口转发
远程端口转发
和 本地端口转发相比,这次的图里,SSH Server 和 SSH Client 的位置对调了一下,但是数据流依然是一样的。我们在 LdapClientHost 上的应用将数据发送到本机的 7001 端口上,而本机的 SSH Server 会将 7001 端口收到的数据加密并转发到 LdapServertHost 的 SSH Client 上。 SSH Client 会解密收到的数据并将之转发到监听的 LDAP 389 端口上,最后再将从 LDAP 返回的数据原路返回以完成整个流程。
看到这里,你是不是会有点糊涂了么?为什么叫本地转发,而有时又叫远程转发?这两者有什么区别?

本地转发与远程转发的对比与分析

不 错,SSH Server,SSH Client,LdapServertHost,LdapClientHost,本地转发,远程转发,这么多的名词的确容易让人糊涂。让我们来分析一下其 中的结构吧。首先,SSH 端口转发自然需要 SSH 连接,而 SSH 连接是有方向的,从 SSH Client 到 SSH Server 。而我们的应用也是有方向的,比如需要连接 LDAP Server 时,LDAP Server 自然就是 Server 端,我们应用连接的方向也是从应用的 Client 端连接到应用的 Server 端。如果这两个连接的方向一致,那我们就说它是本地转发。而如果两个方向不一致,我们就说它是远程转发。
我们可以回忆上面的两个例子来做个对照。
本地转发时:
LdapClientHost 同时是应用的客户端,也是 SSH Client,这两个连接都从它指向 LdapServertHost(既是 LDAP 服务端,也是 SSH Server)。
远程转发时:
LdapClientHost 是应用的客户端,但却是 SSH Server ;而 LdapServertHost 是 LDAP 的服务端,但却是 SSH Client 。这样两个连接的方向刚好相反。
另 一个方便记忆的方法是,Server 端的端口都是预定义的固定端口(SSH Server 的端口 22,LDAP 的端口 389),而 Client 端的端口都是动态可供我们选择的端口(如上述例子中选用的 7001 端口)。如果 Server 端的两个端口都在同一台机器,Client 端的两个端口都在另一台机器上,那么这就是本地连接;如果这四个端口交叉分布在两个机器上,每台机器各有一个 Server 端端口,一个 Client 端端口,那就是远程连接。
弄清楚了两者的区别之后,再来看看两者的相同之处。如果你所在的环 境下,既允许 LdapClientHost 发起 SSH 连接到 LdapServerHost,也允许 LdapServerHost 发起 SSH 连接到 LdapClientHost 。那么这时我们选择本地转发或远程转发都是可以的,能完成一样的功能。
接着让我们来看个进阶版的端口转发。我们之前涉及到的各种连接 / 转发都只涉及到了两台机器,还记得我们在本地转发中提到的一个问题么?本地转发命令中的 <remote host> 和 <SSH hostname> 可以是不同的机器么?
ssh -L <local port>:<remote host>:<remote port> <SSH hostname>
答案是可以的!让我们来看一个涉及到四台机器 (A,B,C,D) 的例子。
图 4. 多主机转发应用
多主机转发应用
在 SSH Client(C) 执行下列命令来建立 SSH 连接以及端口转发:
$ ssh -g -L 7001:<B>:389 <D>
然 后在我们的应用客户端(A)上配置连接机器(C )的 7001 端口即可。注意我们在命令中指定了“ -g ”参数以保证机器(A)能够使用机器(C)建立的本地端口转发。而另一个值得注意的地方是,在上述连接中,(A)<-> (C) 以及 (B)<->(D) 之间的连接并不是安全连接,它们之间没有经过 SSH 的加密及解密。如果他们之间的网络并不是值得信赖的网络连接,我们就需要谨慎使用这种连接方式了。

第三部分 其他类型的转发

动态转发实例分析

恩, 动态转发,听上去很酷。当你看到这里时,有没有想过我们已经讨论过了本地转发,远程转发,但是前提都是要求有一个固定的应用服务端的端口号,例如前面例子 中的 LDAP 服务端的 389 端口。那如果没有这个端口号怎么办?等等,什么样的应用会没有这个端口号呢?嗯,比如说用浏览器进行 Web 浏览,比如说 MSN 等等。
当我们在一个不安全的 WiFi 环境下上网,用 SSH 动态转发来保护我们的网页浏览及 MSN 信息无疑是十分必要的。让我们先来看一下动态转发的命令格式:
$ ssh -D <local port> <SSH Server>
例如:
$ ssh -D 7001 <SSH Server>
图 5. 动态端口转发
动态端口转发
似乎很简单,我们依然选择了 7001 作为本地的端口号,其实在这里 SSH 是创建了一个 SOCKS 代理服务。来看看帮助文档中对 -D 参数的描述:
-D port 
 This works by allocating a socket to listen to port on the local 
 side, and whenever a connection is made to this port, the con- 
 nection is forwarded over the secure channel, and the applica- 
 tion protocol is then used to determine where to connect to from 
 the remote machine.  Currently the SOCKS4 and SOCKS5 protocols 
 are supported, and ssh will act as a SOCKS server.  Only root 
 can forward privileged ports.  Dynamic port forwardings can also 
 be specified in the configuration file.
之后的使用就简单了,我们可以直接使 用 localhost:7001 来作为正常的 SOCKS 代理来使用,直接在浏览器或 MSN 上设置即可。在 SSH Client 端无法访问的网站现在也都可以正常浏览。而这里需要值得注意的是,此时 SSH 所包护的范围只包括从浏览器端(SSH Client 端)到 SSH Server 端的连接,并不包含从 SSH Server 端 到目标网站的连接。如果后半截连接的安全不能得到充分的保证的话,这种方式仍不是合适的解决方案。

X 协议转发实例分析

好了,让我们来看最后一个例子 – X 协议转发。
我 们日常工作当中,可能会经常会远程登录到 Linux/Unix/Solaris/HP 等机器上去做一些开发或者维护,也经常需要以 GUI 方式运行一些程序,比如要求图形化界面来安装 DB2/WebSphere 等等。这时候通常有两种选择来实现:VNC 或者 X 窗口,让我们来看看后者。
使用 X 窗口通常需要分别安装:X Client 和 X Server 。在本例中我们的 X Client 就是所访问的远程 Linux/Unix/Solaris/HP,而我们的 X Server 则是发起访问的本地机器(例如你面前正在使用的笔记本或台式机)。把 X Client 端的 X 窗口显示在 X Server 端需要先行在 X Client 端指定 X Server 的位置,命令格式如下:
export DISPLAY=<X Server IP>:<display #>.<virtual #>
例如:
export DISPLAY=myDesktop:1.0
然后直接运行 X 应用即可,X 窗口就会自动在我们的本地端打开。
一 切运行正常,但是,这时候 IT 部门突然在远程 Linux/Unix/Solaris/HP 前面加了一道防火墙。非常不幸的是,X 协议并不在允许通过的列表之内。怎么办?只能使用 VNC 了么?不,其实只要使用了 SSH 端口转发即可通过,同时也对 X 通讯数据做了加密,真是一举两得。(当然,使用此方法前最好先咨询相关 IT 部门是否符合相应的安全条例,以免造成违规操作。)
建立命令也很简单,直接从本地机器(X Server 端)发起一个如下的 SSH 连接即可:
$ ssh -X <SSH Server>
图 5. X 转发
X 转发
建立连接之后就可以直接运行远程的 X 应用。注意建立 X 转发之后会自动设置 DISPLAY 环境变量,通常会被设置成localhost:10.0,我们无需也不应该在连接之后再进行修改此环境变量。
一个比较常见的场景是,我们的本地机器是 Windows 操作系统,这时可以选择开源的 XMing 来作为我们的 XServer,而 SSH Client 则可以任意选择了,例如 PuTTY,Cygwin 均可以配置 访问 SSH 的同时建立 X 转发。

第四部分 总结

至 此,我们已经完成了本地端口转发,远程端口转发,动态端口转发以及 X 转发的介绍。回顾起来,总的思路是通过将 TCP 连接转发到 SSH 通道上以解决数据加密以及突破防火墙的种种限制。对一些已知端口号的应用,例如 Telnet/LDAP/SMTP,我们可以使用本地端口转发或者远程端口转发来达到目的。动态端口转发则可以实现 SOCKS 代理从而加密以及突破防火墙对 Web 浏览的限制。对于 X 应用,无疑是 X 转发最为适用了。虽然每一部分我们都只是简单的介绍了一下,但如果能灵活应用这些技巧,相信对我们的日常生活 / 工作也是会有所帮助的。

from  http://www.dkys.org/archives/554.html