今天虚拟机装了个 centos8 ,用xshell配置密钥登录一直报错:“xshell 所选的用户密钥未在远程主机上注册”,很纳闷,这个操作操作了好多次,不应该错啊。
好吧,检查下日志吧
tail -f /var/log/secure
Nov 15 23:41:51 MiWiFi-RA72-srv sshd[98343]: Authentication refused: bad ownership or modes for directory /home/centos/.ssh
Nov 15 23:41:53 MiWiFi-RA72-srv sshd[98343]: Authentication refused: bad ownership or modes for directory /home/centos/.ssh
Nov 15 23:41:57 MiWiFi-RA72-srv sshd[98343]: Authentication refused: bad ownership or modes for directory /home/centos/.ssh
原因
sshd为了安全,对属主的目录和文件权限有所要求。如果权限不对,则ssh的免密码登陆不生效。
用户目录权限为 755 或者 700,就是不能是77x。
.ssh目录权限一般为755或者700。
rsa_id.pub 及authorized_keys权限一般为644
rsa_id权限必须为600
忽然想起来 新建 .ssh 目录是顺手给赋 了个777,手欠啊
只要原因了,就修改吧
修改目录和文件权限
chmod 700 .ssh
chmod 600 authorized_keys
重启sshd
systemctl restart sshd
完美解决。
重写下操作步骤吧,万一哪天忘了呢
方法一
1、打开xshell 工具--新建用户密钥生成向导
输入密码(这个密码不是主机用户的密码可以不一样的)
保存到公钥,备用
主机上操作
登陆主机在home目录下新建 .ssh
mkdir .ssh
chmod 700 .ssh
在 .ssh 下新建公钥文件authorized_keys
chmod 600 authorized_keys
把刚才备份的公钥复制进authorized_keys 文件 保存
重启sshd
systemctl restart sshd
--------------------------------------------------------------------------------------------------------
方法二 主机上 用 ssh-keygen 命令生成 公钥私钥
1、
[centos@MiWiFi-RA72-srv ~]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/centos/.ssh/id_rsa):
Enter passphrase (empty for no passphrase): --------输入密码
Enter same passphrase again: -----确认密码
Your identification has been saved in /home/centos/.ssh/id_rsa.
Your public key has been saved in /home/centos/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:copIJmJi+7ZFJSPF6PhJbiWGi9A0ww9GXmujP+aOZlE centos@MiWiFi-RA72-srv
The key's randomart image is:
+---[RSA 3072]----+
| o. +. |
| .Bo.o |
| +=*+o . |
|.o.BEo+ |
|*oX.+.. S |
|*=oB.. + |
| .o.=.. |
| +=.. |
| oo++ |
+----[SHA256]-----+
把公钥写入authorized_keys
cat id_rsa.pub >authorized_keys
重启 sshd
重启sshd
systemctl restart sshd
2、
xshell 导入私钥
配置登陆
选择密钥
密钥登陆成功
----------------------------
可以关闭密码登陆
vi sshd_config
PasswordAuthentication no ---ssh用密码就不能登陆了
重启sshd
systemctl restart sshd
用账号密码登陆把认证失败,日志如下
sshd[100028]: Connection closed by authenticating user centos 192.168.31.12 port 48692 [preauth]