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

时间:2022-03-28 02:17:33

生成PublicKey

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 for no passphrase):
 #重复密码短语
 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:
 aa:8b::::ad:b5::ca:::b9::e1::e1 root@localhost.localdomain
 The key's randomart image is:
 +--[ RSA ]----+
 |    .o.          |
 |    ..   . .     |
 |   .  . . o o    |
 | o.  . . o E     |
 |o.=   . S .      |
 |.*.+   .         |
 |o.*   .          |
 | . + .           |
 |  . o.           |
 +-----------------+

复制密钥对

| 也可以手动在客户端建立目录和authorized_keys,注意修改权限

 #复制公钥到无密码登录的服务器上,22端口改变可以使用下面的命令
 #ssh-copy-id -i ~/.ssh/id_rsa.pub "-p 10022 user@server"
 ss h-copy-id -i ~/.ssh/id_rsa.pub root@192.168.15.241

修改SSH配置文件

 #编辑sshd_config文件
 vi /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

转载 http://wsgzao.github.io/post/ssh/