温馨提示×

centos怎么关闭ssh访问

小樊
42
2026-09-14 20:43:41
栏目: 智能运维

在 CentOS 上“关闭 SSH 访问”通常有几种不同层级的做法,取决于你是完全禁用 SSH 服务,还是禁止某些用户/IP 访问。下面按常见场景说明:


一、彻底关闭 SSH 服务(最常用)

CentOS 6 及以前(SysVinit)

service sshd stop
chkconfig sshd off

CentOS 7 / 8 / Stream(systemd)

systemctl stop sshd
systemctl disable sshd

这样重启后 SSH 也不会自动启动,你将无法通过 SSH 远程登录服务器

✅ 建议:如果是云服务器,请确认有控制台(VNC)可用,否则可能“把自己锁外面”。


二、只允许本地登录,禁止远程 SSH(不卸载服务)

修改 SSH 配置文件:

vi /etc/ssh/sshd_config

添加或修改:

# 禁止所有远程登录
PermitRootLogin no
PasswordAuthentication no

或者直接监听一个不存在的地址:

ListenAddress 127.0.0.1

然后重启:

systemctl restart sshd

三、通过防火墙关闭 SSH 端口(22)

使用 firewalld(CentOS 7+)

systemctl stop firewalld
# 或只关闭 22 端口
firewall-cmd --permanent --remove-service=ssh
firewall-cmd --reload

使用 iptables(老版本)

iptables -A INPUT -p tcp --dport 22 -j DROP
service iptables save

四、禁止特定用户 SSH 登录

编辑:

vi /etc/ssh/sshd_config
DenyUsers user1 user2
# 或
DenyGroups dev

重启:

systemctl restart sshd

五、临时关闭 SSH(应急)

systemctl stop sshd

⚠️ 重启后会恢复(如果未 disable)


推荐做法总结

需求 方法
完全不用 SSH systemctl disable sshd
临时维护 systemctl stop sshd
禁止外网访问 防火墙关闭 22
限制用户 DenyUsers

如果你能告诉我:

  • CentOS 版本
  • 云服务器还是物理机
  • 是想“完全关闭”还是“限制访问”

我可以给你更精确的操作命令。

0