Skip to the content.

说明:本文以Ubuntu Server 14.04为例,其他版本操作系统处理方式基本相同,单具体文件位置和命令脚本可能有差别。

sshd服务端配置

配置文件位置

一般在/etc/ssh/sshd_config

安全配置建议

禁止root用户登陆

在配置文件中将PermitRootLogin参数值修改为no

不使用默认端口

在配置文件中将Port参数值修改为对应的端口,例如:

Port 21345

禁止使用密码登陆

在配置文件中将PasswordAuthentication参数值修改为no

允许使用RSA秘钥登陆

在配置文件中将RSAAuthentication参数值修改为yes

重启sshd服务

service sshd restart

使用RSA秘钥登陆

假设ssh服务器端的域名为ssh-server,本地的客户端域名为ssh-cient,操作步骤如下:

1. 服务器端开启使用密码登陆和RSA登陆,即设置:

PasswordAuthentication yes
RSAAuthentication yes

并重启sshd服务

2. 在客户端上运行以下命令设置RSA秘钥对

ssh-keygen

中间过程可以一路回车,有兴趣的可以自行尝试调整中间参数,运行后显示如下:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/wangrui/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/wangrui/.ssh/id_rsa.
Your public key has been saved in /home/wangrui/.ssh/id_rsa.pub.
The key fingerprint is:
c8:62:91:fb:be:6f:13:51:e2:9b:9f:a1:e0:ed:84:1e wangrui@dev-host
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|     .  . .      |
|    o  . o       |
|     + .o        |
|    + o S+       |
|   . o..+ .      |
|     .Eo.+ o     |
|     o.o= o      |
|      +=o.       |
+-----------------+

最终得到两个文件:

<home>/.ssh/id_rsa  
<home>/.ssh/id_rsa.pub

这两个文件id_rsa.pub为公钥,id_rsa为私钥。私钥由客户端自行保存,公钥可以存放在任何一台你需要登陆的服务器上。

3. 存放公钥至服务器

可以通过ssh-copy-id命令保存公钥,在客户端上运行:

ssh-copy-id wangrui@ssh-server -p <port_num>

成功的话,你可能会得到类似下面的提示:

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/toboto/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
wangrui@ssh-server's password: 

Number of key(s) added:        1

Now try logging into the machine, with:   "ssh -p <port_num> 'wangrui@ssh-server'"
and check to make sure that only the key(s) you wanted were added.

上面的操作的结果是将公钥中的内容加入了服务器端对应用户<home>/.ssh/authorized_keys文件中,所以如果上面的操作不能成功,也可以将公钥复制到这个文件中。

4. 尝试直接登陆

ssh wangrui@ssh-server -p <port_num>

此时应该不需要输入密码即可完成登陆。

5. 关闭服务器端的密码登陆(建议操作)

PasswordAuthentication no
RSAAuthentication yes