问题:当我尝试ssh到一台远程服务器时,ssh客户端登陆失败并提示“connection closed by x.x.x.x”。在ssh服务器那端,我看到这样的错误消息:“sshd error: could not load host key.”。这发生了什么问题,我怎样才能修复该错误?
该ssh连接错误的详细症状如下。
ssh客户端方面:当你尝试ssh到一台远程主机时,你没有看见登录屏幕,你的ssh连接就立即关闭,并提示此消息:“connection closed by x.x.x.x”。
ssh服务器方面:在系统日志中,你看到如下错误消息(如,在debian/ubuntu上,/var/log/auth.log)。
oct 16 08:59:45 openstack sshd[1214]: error: could not load host key: /etc/ssh/ssh_host_rsa_key
oct 16 08:59:45 openstack sshd[1214]: error: could not load host key: /etc/ssh/ssh_host_dsa_key
oct 16 08:59:45 openstack sshd[1214]: error: could not load host key: /etc/ssh/ssh_host_ecdsa_key
oct 16 08:59:45 openstack sshd[1214]: fatal: no supported key exchange algorithms [preauth]
导致该问题的根源是,sshd守护进程不知怎么地不能加载ssh主机密钥了。
当openssh服务器第一次安装到linux系统时,ssh主机密钥应该会自动生成以供后续使用。如果,不管怎样,密钥生成过程没有成功完成,那就会导致这样的ssh登录问题。

让我们检查能否在相应的地方找到ssh主机密钥。
$ ls -al /etc/ssh/ssh*key
如果ssh主机密钥在那里找不到,或者它们的大小被截断成为0(就像上面那样),你需要从头开始重新生成主机密钥。
<a target="_blank"></a>
在debian、ubuntu或其衍生版上,你可以使用dpkg-reconfigure工具来重新生成ssh主机密钥,过程如下:
$ sudo rm -r /etc/ssh/ssh*key
$ sudo dpkg-reconfigure openssh-server
在centos、rhel或fedora上,你所要做的是,删除现存(有问题的)密钥,然后重启sshd服务。
$ sudo systemctl restart sshd
另外一个重新生成ssh主机密钥的方式是,使用ssh-keygen命令来手动生成。
$ sudo ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key
$ sudo ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key
$ sudo ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key
在生成新的ssh主机密钥后,确保它们能在/etc/ssh目录中找到。此时,不必重启sshd服务。
现在,再试试ssh到ssh服务器吧,看看问题是否已经离你而去了。
原文发布时间:2014-11-14
本文来自云栖合作伙伴“linux中国”