Centos9-SSH免密登录配置-修改22端口-关闭密码登录
- 生成秘钥对
- 将公钥信息存进authorized_keys
- 测试登录
- 查询访问记录、比对指纹
- 更换22访问端口
- 关闭账号密码登录
生成秘钥对
- 生成密钥对,指定 备注 和 文件目录
- 命令执行后,默认两次回车,不设置秘钥使用密码
ssh-keygen -t rsa -b 4096 -C "wangyongji" -f /root/.ssh/wangyongji_key
ssh-keygen -t rsa -b 4096 -C "xiaoming" -f /root/.ssh/xiaoming_key
ssh-keygen -t rsa -b 4096 -C "xiaoli" -f /root/.ssh/xiaoli_key
将公钥信息存进authorized_keys
- 将上述生活的 .pub 公钥文件内的信息,追加到 /root/.ssh/authorized_keys 文件中
cat /root/.ssh/wangyongji_key.pub >> /root/.ssh/authorized_keys
cat /root/.ssh/xiaoming_key.pub >> /root/.ssh/authorized_keys
cat /root/.ssh/xiaoli_key.pub >> /root/.ssh/authorized_keys
测试登录
/root/.ssh/wangyongji_key
/root/.ssh/xiaoming_key
/root/.ssh/xiaoli_key
-
访问者
-
通过ssh命 $ ssh -i /xxx/xxx/wangyongji_key root@47.95.230.189
-
或者ssh工具(我用的xshell)进行登录,输入用户名后,选择 PublickKey模式登录,选择秘钥文件
查询访问记录、比对指纹
- 查询访问记录 RSA SHA256: 后面的内容就是访问者对应公钥的指纹
- 下面是实操返回内容
$ cat /var/log/secure | grep "Accepted publickey"
$ journalctl -u sshd | grep "Accepted publickey"#识别读取一条完整记录,公钥对应指纹内容就是
#IeC0b/zth0eHZd0LE6J4gidbkBQcW73VMrdrbNSLxn0[root@iZ2ze0h85pej6iyngxg8mqZ ~]# cat /var/log/secure | grep "Accepted publickey"
Jan 12 16:38:51 iZ2ze0h85pej6iyngxg8mqZ sshd[120744]: Accepted publickey for root from 36.97.56.131 port 59492 ssh2: RSA SHA256:IeC0b/zth0eHZd0LE6J4gidbkBQcW73VMrdrbNSLxn0
Jan 12 16:38:52 iZ2ze0h85pej6iyngxg8mqZ sshd[120753]: Accepted publickey for root from 36.97.56.131 port 59503 ssh2: RSA SHA256:IeC0b/zth0eHZd0LE6J4gidbkBQcW73VMrdrbNSLxn0
- 计算公钥指纹,进行比对
- 比对结果为 wangyongji_key.pub ,备注信息为 wangyongji
[root@iZ2ze0h85pej6iyngxg8mqZ ~]# ssh-keygen -lf /root/.ssh/wangyongji_key.pub
4096 SHA256:IeC0b/zth0eHZd0LE6J4gidbkBQcW73VMrdrbNSLxn0 wangyongji (RSA)[root@iZ2ze0h85pej6iyngxg8mqZ ~]# ssh-keygen -lf /root/.ssh/xiaoming_key.pub
4096 SHA256:h0RNkq0LZ3lgyNcyE2uLbfiSdql4ITWddlmfrmyU31E xiaoming (RSA)[root@iZ2ze0h85pej6iyngxg8mqZ ~]# ssh-keygen -lf /root/.ssh/xiaoli_key.pub
4096 SHA256:Kth9tVKCBtWeVoK7r8AI1ageV0n8kUhwLDHe+QwWUdY xiaoli (RSA)
更换22访问端口
- 修改配置文件 sshd_config
- 注意防火墙开放此端口
sudo vim /etc/ssh/sshd_config#文件内搜索 Port
/Port#放开注释,修改端口,注意防火墙开放此端口
Port 27520
- 重启SSH服务
- $ sudo systemctl restart sshd
关闭账号密码登录
sudo vim /etc/ssh/sshd_config#文件内搜索 PasswordAuthentication
/PasswordAuthentication#修改内容 no 进行密码登录
PasswordAuthentication no# PasswordAuthentication yes # 默认启用密码登录
# PubkeyAuthentication yes # 默认启用公钥认证
- 重启SSH服务
- $ sudo systemctl restart sshd