Linux-SSH密钥登录

1. 制作密钥对

[root@host ~]$ ssh-keygen  <== 建立密钥对
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): <== 按 Enter
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): <== 输入密钥锁码,或直接按 Enter 留空
Enter same passphrase again: <== 再输入一遍密钥锁码
Your identification has been saved in /root/.ssh/id_rsa. <== 私钥
Your public key has been saved in /root/.ssh/id_rsa.pub. <== 公钥
The key fingerprint is:
0f:d3:e7:1a:1c:bd:5c:03:f1:19:f1:22:df:9b:cc:08 root@host

2. 在服务器上安装公钥

[root@host ~]$ cd .ssh
[root@host .ssh]$ cat id_rsa.pub >> authorized_keys

[root@host .ssh]$ chmod 600 authorized_keys
[root@host .ssh]$ chmod 700 ~/.ssh

3. 设置 SSH,打开密钥登录功能

# 编辑 /etc/ssh/sshd_config 文件,进行如下设置:
RSAAuthentication yes
PubkeyAuthentication yes

另外,请留意 root 用户能否通过 SSH 登录:

PermitRootLogin yes

当你完成全部设置,并以密钥方式登录成功后,再禁用密码登录

PasswordAuthentication no

最后,重启 SSH 服务:

[root@host .ssh]$ service sshd restart

4. 将私钥下载到客户端,然后转换为 PuTTY 能使用的格式

使用 WinSCP、SFTP 等工具将私钥文件 id_rsa 下载到客户端机器上。然后打开 PuTTYGen,单击 Actions 中的 Load 按钮,载入你刚才下载到的私钥文件。如果你刚才设置了密钥锁码,这时则需要输入。

载入成功后,PuTTYGen 会显示密钥相关的信息。在 Key comment 中键入对密钥的说明信息,然后单击 Save private key 按钮即可将私钥文件存放为 PuTTY 能使用的格式。

今后,当你使用 PuTTY 登录时,可以在左侧的 Connection -> SSH -> Auth 中的 Private key file for authentication: 处选择你的私钥文件,然后即可登录了,过程中只需输入密钥锁码即可。

Last updated