排查主机原因
如果你在尝试通过 SSH 连接到新购买的 CentOS 7 服务器时出现“connection refused”错误,可能有以下几种原因。
以下是一些可能的解决方法:
1.检查 SSH 服务是否运行
SSH 可能没有在 CentOS 7 服务器上运行。要检查是否正在运行,请使用以下命令: systemctl status sshd 如果输出显示 SSH 服务没有运行,请使用以下命令启动它: systemctl start sshd
2.检查防火墙设置
默认情况下,CentOS 7 服务器启用了防火墙。如果防火墙不允许 SSH 连接,则可能会出现“connection refused”错误。要检查防火墙设置,请使用以下命令: firewall-cmd --list-all 如果输出显示防火墙正在运行并且没有允许 SSH 连接,请使用以下命令添加 SSH 服务到防火墙规则中:
firewall-cmd --permanent --add-service=ssh
firewall-cmd --reload
3.检查 SSH 配置文件
SSH 配置文件可能已被更改,导致无法连接。要检查 SSH 配置文件,请使用以 下命令: nano /etc/ssh/sshd_config 然后确认以下设置是否正确:
Port 22
PermitRootLogin yes
PasswordAuthentication yes
如果需要更改这些设置,请保存文件并重新启动 SSH 服务:
systemctl restart sshd
systemctl status sshd
如果你已经尝试了上述解决方法,但仍然无法连接到 CentOS 7 服务器,你可以尝试以下几种方法:
4.检查网络连接
确保你的计算机和 CentOS 7 服务器都已连接到互联网,并且可以相互通信。
5.检查 SSH 配置文件的权限
确保 /etc/ssh/sshd_config 文件的权限设置正确,即只有 root 用户可以读取和写入该文件。可以使用以下命令检查文件权限: ls -l /etc/ssh/sshd_config 如果权限设置不正确,请使用以下命令进行更改: chmod 600 /etc/ssh/sshd_config
7. 检查 SELinux(CentOS 7 高发原因)
CentOS 7 默认启用 SELinux,它可能在系统层面阻止 SSH 守护进程绑定 22 端口。检查:
# 查看 SELinux 状态
getenforce
# 如果输出 Enforcing,临时关闭测试:
setenforce 0
# 再试 SSH 连接。如果此时能连上,说明是 SELinux 的问题
永久修复(不推荐直接关掉 SELinux):
# 检查 SSH 端口的 SELinux 标签
semanage port -l | grep ssh
# 如果 22 端口没有 ssh_port_t 标签,手动添加:
semanage port -a -t ssh_port_t -p tcp 22
注意:很多 VPS 运营商的系统模板默认禁用了 SELinux(/etc/selinux/config 中 SELINUX=disabled),但如果你用的是官方 ISO 安装的纯净 CentOS 7,SELinux 很可能是开启的。
8. VPS 控制台终极排查
如果以上方法全部无效,登录 VPS 服务商的网页控制台(VNC),直接在服务器上检查:
# 检查 SSHD 是否真的在监听
ss -tlnp | grep 22
# 如果没输出,说明 SSHD 根本没启动
systemctl start sshd
systemctl enable sshd
# 检查是否有其他程序占用了 22 端口
lsof -i :22
如果 VNC 也连不上,那就是系统层面出了问题——联系 VPS 服务商或直接重装系统。
6.尝试使用其他 SSH 客户端
如果你使用的是 Putty 或类似的 SSH 客户端,并且无法连接到 CentOS 7 服务器,请尝试使用其他 SSH 客户端,例如 OpenSSH。
如果以上 8 步全部无效,最后的手段:通过 VPS 服务商面板重装系统。对于新买的机器,重装比你继续排查要省时间得多。装好后第一件事就是 systemctl enable sshd && systemctl start sshd,再配防火墙。
相关阅读:Linux 放行端口、Nginx 配置详解