SSH 使用密钥登录并禁止口令登录实践

Paste_Image.png

生成PublicKey
建议设置并牢记passphrase密码短语,以Linux生成为例

Linux:ssh-keygen -t rsa
[私钥 (id_rsa) 与公钥 (id_rsa.pub)]
Windows:SecurCRT/Xshell/PuTTY
[SSH-2 RSA 2048]

生成SSH密钥对

ssh-keygen -t rsa

Generating public/private rsa key pair.

Enter file in which to save the key (/root/.ssh/id_rsa): //建议直接回车使用默认路径

Enter passphrase (empty forno passphrase): //输入密码短语(留空则直接回车)

Enter same passphrase again: //重复密码短语

Your identification has been saved in/root/.ssh/id_rsa.

Yourpublic key has been saved in/root/.ssh/id_rsa.pub.

The key fingerprint is:

aa:8b:61:13:38:ad:b5:49:ca:51:45:b9:77:e1:97:e1 root@localhost.localdomain

The key's randomart image is:

+--[ RSA 2048]----+

| .o. |

| .. . . |

| . . . o o |

| o. . . o E |

|o.= . S . |

|.*.+ . |

|o.* . |

| . + . |

| . o. |

+-----------------+
在 /root/.ssh/... 下创建 <strong> authorized_keys </strong> 文件,然后执行:

cat id_rsa.pub >> authorized_keys

修改SSH配置文件

编辑sshd_config文件

vim /etc/ssh/sshd_config

禁用密码验证

PasswordAuthentication no

启用密钥验证

RSAAuthentication yes
PubkeyAuthentication yes

指定公钥数据库文件

AuthorsizedKeysFile.ssh/authorized_keys

重启SSH服务前建议多保留一个会话以防不测

RHEL/CentOS系统

service sshd restart

Ubuntu系统

service ssh restart

debian系统

/etc/init.d/ssh restart

手动增加管理用户
可以在== 后加入用户注释标识方便管理

echo 'ssh-rsa XXXX'>>/root/.ssh/authorized_keys

复查

cat /root/.ssh/authorized_keys

推荐阅读更多精彩内容