Last Updated on 2025-07-07 by Lee
Ubuntu22禁止密码登录无效,是很多人遇到的问题。最近我也遇到了密码禁用无效的问题。有什么解决办法吗,有的,按照我说的方法做就行。
最近又购买了一台的云主机,使用的Ubuntu22.04 LTS系统。
按照往常的操作,拿到root账号密码后以密码认证方式远程登录到了Ubuntu22系统。
做完系统补丁升级,软件配置,防火墙等等后,开始配置ssh密钥登录,禁止密码登录。
但是在“sshd.config”文件里更改参数后重启sshd服务,Ubuntu22禁止密码登录无效。使用远程登录依然是使用密码而不是已经配置好的密钥登录方式。
我之前配置Ubuntu18的时候就没有这种情况发生。 问题应该还是出在Ubuntu22上。
后来我google搜索了下,找到了两种方法,原来是在“sshd_config.d”目录下有个“50-cloud-init.conf”文件,里面有一行“PasswordAuthentication yes”。这一行,会影响sshd.config文件里的配置。
另外在“askubuntu”社区里找到了老外给的答案,有兴趣可以看看。
https://askubuntu.com/questions/1516262/why-is-50-cloud-init-conf-created
解决方法1:在sshd.config里,把“PasswordAuthentication no”放到首行。
解决方法2:删除 /etc/ssh/ssh_config.d/50-cloud-init.conf文件里的“PasswordAuthentication yes”。
留着“PasswordAuthentication yes”觉得不放心,我使用第二种方法解决ubuntu22禁用密码登录无效。
以下是记录怎么配置ssh密码认证方式远程登录的过程,以备以后再次操作的时候可以回顾下。
使用ssh-keygen命令生成密钥对。
root@lee:~# ssh-keygen
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:
SHA256:+4yY44DV0zKOKJVXc6zgC9fhdq4P/waxQ96MIHdxBt0 root@lee
The key's randomart image is:
+---[RSA 3072]----+
| .o . |
| .. + E |
| . + o+ |
| o.*o*+ |
| + =oX=S* |
| . B = **.o |
|. o + o oo |
| . ..* +. |
| .=o+o+ |
+----[SHA256]-----+
root@lee:~#
上面的操作步骤是使用ssh-keygen生成公钥和私钥。密钥对默认生成在用户家目录下.ssh文件夹里。
我使用的是root账号,所以密钥对在/root/.ssh/文件夹下。
进入.ssh文件夹,拷贝公钥id_rsa.pub到authorized_keys文件里。
root@lee:~# cd .ssh/
root@lee:~/.ssh# ll
total 16
drwx------ 2 root root 4096 Jun 27 02:12 ./
drwx------ 5 root root 4096 Jun 27 02:10 ../
-rw------- 1 root root 0 Jun 27 02:08 authorized_keys
-rw------- 1 root root 2590 Jun 27 02:12 id_rsa
-rw-r--r-- 1 root root 562 Jun 27 02:12 id_rsa.pub
root@lee:~/.ssh# cat id_rsa.pub >> authorized_keys
root@lee:~/.ssh#
拷贝id_rsa.pub公钥到authorized_keys的操作,我理解成给大门设置了一把可以刷卡的锁头。然后私钥就是门禁卡,以后进入大门不需要手动输入密码,而是直接刷卡就行。
现在编辑下sshd配置文件。
vi /etc/ssh/sshd_config
使用vim编辑器,更改以下相关参数。
其他Linux系统一般sshd.config文件里默认也有这三行,找到它们,删除注释符#,按照需求更改后面值“no”或“yes”。
PermitRootLogin yes # 允许root账号远程登录
PubkeyAuthentication yes # 使用密钥认证方式登录
PasswordAuthentication no # 禁用密码认证方式登录
更改完成后,按ESC键wq保存,重启sshd服务。
root@lee:~#systemctl restart sshd
然后下载私钥id_rsa到本地以便准备用xshell等远程工具登录使用。
正常的情况下,经过以上配置后,就禁止了密码登录,强制使用密钥方式登录了。我之前经常使用CentOS7和最近使用的Ubuntu18通过这样的配置用密钥认证方式登录是没有问题的。
但是,Ubuntu22这样配置后使用远程登录,依然是使用密码登录,而不是密钥登录。
我通过删除50-cloud-init.conf文件里的参数来解决这个问题。
以下操作是ubuntu22远程ssh登录禁用密码无效的操作记录。
首先需要切换到/etc/ssh/sshd_config.d/目录,删除“50-cloud-init.conf”文件里“PasswordAuthentication yes”。
root@lee:~/.ssh# cd /etc/ssh/sshd_config.d/
root@lee:/etc/ssh/sshd_config.d# vi 50-cloud-init.conf
删除“50-cloud-init.conf”里的“PasswordAuthentication yes”后重启sshd服务。
root@lee:~# systemctl restart sshd
好了,至此ubuntu22禁用密码登录成功,可以使用xshell等工具就可以以密钥认证方式登录服务器了。