记一次客户端连接Docker容器 sshd 报错Permission denied, please try again.的问题
【背景】
在一次需求中需要实现 Docker 启动 CentOS7.9,并在容器内安装 sshd 实现外部客户端可以访问。sshd 是打包好可直接运行的二进制文件,并且 sshd_config 也是提供的现成的,这也为后边出现问题做了铺垫。我这边首先是把 sshd 的二进制可执行文件拷贝到了/usr/sbin/sshd,然后 sshd_config 拷贝到了/etc/ssh/sshd_config。
【报错与解决方案】
第一次执行,由于使用的 Docker 容器启动,并且 CMD命令为/bin/bash,所以只能通过启动二进制文件来操作。
/usr/sbin/sshd
报错
Privilege separation user sshd does not exist
解决方案
/usr/sbin/groupadd sshd /usr/sbin/useradd -g sshd sshd
再次启动报错如下:
Could not load host key: /etc/ssh/ssh_host_rsa_key Could not load host key: /etc/ssh/ssh_host_ecdsa_key Could not load host key: /etc/ssh/ssh_host_ed25519_key sshd: no hostkeys available -- exiting.
这是因为配置文件中设置了包含计算机私人密钥的文件
HostKey /etc/ssh/ssh_host_rsa_key HostKey /etc/ssh/ssh_host_ecdsa_key HostKey /etc/ssh/ssh_host_ed25519_key
解决方案
1、询问 sshd_config 提供人,让他提供密钥文件
2、使用sshd-keygen -A生成密钥
再次启动报错如下
Permissions 0777 for '/etc/ssh/ssh_host_rsa_key' are too open. It is required that your private key files are NOT accessible by others. This private key will be ignored. key_load_private: bad permissions
这是因为配置文件权限过高,解决方案
chmod 600 /etc/ssh/*key*
继续启动成功,客户端远程连接失败,报错
Permission denied, please try again.
到这里就比较棘手了,一直没有找到解决办法,本身对于 sshd 的启动命令也不是很熟,后来得知可以通过使用 -d 参数前台启动并开启 debug 模式,终于燃起了一丝希望。
首先服务端通过命令/usr/sbin/sshd -d启动
客户端此时连接服务端,日志就会显示在前台页面,从中看到了一条报错
PAM: password authentication failed for root: Authentication failure
果断搜索此报错,终于找到了解决方案,参考https://blog.csdn.net/Daphnisz/article/details/124040904
原因是我的配置文件中开启了UsePAM yes,配置文件是现成的,也就没注意到。
解决方案:
在 pam 中增加 sshd 的配置
vim /etc/pam.d/sshd # 文件内容如下 #%PAM-1.0 auth required pam_sepermit.so auth substack password-auth auth include postlogin # Used with polkit to reauthorize users in remote sessions -auth optional pam_reauthorize.so prepare account required pam_nologin.so account include password-auth password include password-auth # pam_selinux.so close should be the first session rule session required pam_selinux.so close session required pam_loginuid.so # pam_selinux.so open should only be followed by sessions to be executed in the user context session required pam_selinux.so open env_params session required pam_namespace.so session optional pam_keyinit.so force revoke session include password-auth session include postlogin # Used with polkit to reauthorize users in remote sessions -session optional pam_reauthorize.so prepare
然后使用命令 ps aux | grep sshd 查看进程并 kill,重新启动/usr/sbin/sshd -d
客户端重新连接成功,喜大普奔!!!