Back

让SSH支持两步验证

|

为了增加安全性,服务器上关闭了密码登录只允许使用密钥对。可是如果需要在公共电脑上使用服务器,会因为没有私钥而无法登录。

这个时候可以使用Google的Authenticator来平衡安全性与易用性,你需要智能手机一部。

1.下载并在手机上安装Authenticator客户端,Android市场[地址](https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en)。iOS商店[地址](http://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8)。

2.在ubuntu上安装依赖包:[cc lang="bash"]apt-get -yy install gcc mercurial libpam0g-dev[/cc]

3.下载Authenticator服务器端: [cc lang="bash"]wget https://google-authenticator.googlecode.com/files/libpam-google-authenticator-1.0-source.tar.bz2[/cc]

4.编译安装:
[cc lang="bash"]tar jxvf libpam-google-authenticator-1.0-source.tar.bz2[/cc]
[cc lang="bash"]cd libpam-google-authenticator-1.0[/cc]
[cc lang="bash"]make install[/cc]

5.修改ssh的配置文件/etc/ssh/sshd\_config
找到,[cc lang="bash"]ChallengeResponseAuthentication no[/cc] 改为:[cc lang="bash"]ChallengeResponseAuthentication yes[/cc]

6.修改PAM配置文件/etc/pam.d/common-auth
找到,[cc lang="bash"]auth [success=1 default=ignore] pam\_unix.so nullok\_secure[/cc]
在它的上一行添加,[cc lang="bash"]auth required pam\_google\_authenticator.so[/cc]

7.生成authenticator配置文件
直接运行, [cc lang="bash"]google-authenticator[/cc]

会输出一个交互式对话,仔细阅读相关条目,选择Y或者N。
配置完成之后,用浏览器打开输出内容中的那段url地址(你也可以手动输入那些数字串),会得到一个二维码图片,打开手机上的authenticator客户端扫描之,自此配置完成。

原有的key登录方式不会发生变化。当你手边没有私钥的时候,请在SSH客户端中选择Keyboard Interactive验证方式(如果有的话),接下来在Verification code项目上输入手机客户端上出现的验证码,接着输入密码即可。

手机端示意图:
![](https://r2.livy.fun/2025/12/21/6402d0c0a9d93f4341f5f386180509fd.jpg)

一个注意事项,请同时在服务器与手机上开启ntp自动校时服务器。Google把这个项目开源了,所以你可以在很多地方用到这个东西,例如Wordpress就有一个相关[插件](http://wordpress.org/extend/plugins/google-authenticator/)。

No comments yet

Leave a comment

About me

I live in Tasmania, an island a little far from the rest of the world and very close to the sea.
Father of two little girls, have two puppies.

Work

Work in IT industry, AI is my working partner.