linux配置密钥登陆并关闭密码登陆
- 将生成好的公钥上传到服务器
/home/<username>/.ssh/authorized_keys
直接编辑文件
typescript
nano ~/.ssh/authorized_keys然后设置权限
typescript
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys- 改sshd配置将密码登陆方式关闭
先备份
typescript
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak然后打开修改,前面有#的先把#去掉再改参数
typescript
sudo nano /etc/ssh/sshd_config
>>># 1. 彻底关闭密码认证(核心)
>>>PasswordAuthentication no
>>>
>>># 2. 确保公钥认证是开启的
>>>PubkeyAuthentication yes
>>>
>>># 3. (强烈推荐) 禁止 root 用户使用密码登录,但不影响密钥登录
>>># 这能限制 root 账户的暴露面,同时保留你通过密钥登录 root 的应急路径
>>>PermitRootLogin prohibit-password
>>>
>>># 4. (建议) 关闭键盘交互式认证,防止通过 PAM 模块绕过密码限制
>>># 在一些系统上,此项名为 ChallengeResponseAuthentication
>>>KbdInteractiveAuthentication no随后检查语法并重载
ts
sudo sshd -t
sudo systemctl reload sshd先确认当前实际生效的值,而不是看文件里写了什么:
typescript
sudo sshd -T | grep -iE 'passwordauth|pubkeyauth|permitrootlogin|kbdinteractive'sshd -T 打印的是最终合并后真正生效的配置。如果发现 passwordauthentication yes,再查是哪个文件设的:
ts
sudo grep -rniE '^\s*PasswordAuthentication' /etc/ssh/sshd_config /etc/ssh/sshd_config.d/输出:
ts
/etc/ssh/sshd_config:78:PasswordAuthentication no
/etc/ssh/sshd_config.d/50-cloud-init.conf:1:PasswordAuthentication yes最后改,然后校验并重载
typescript
sudo vi /etc/ssh/sshd_config.d/50-cloud-init.conf
>>>PasswordAuthentication no
sudo sshd -t && sudo systemctl reload sshdCAUTION
在确保可以使用密钥登陆前不要关闭修改配置的ssh窗口!!!
开新窗口测试密码登陆是否关闭
typescript
ssh -o PreferredAuthentications=password 服务器名@服务器IP测试私钥登陆是否成功
ts
ssh -i "私钥路径" 服务器名@服务器IP