温馨提示×

centos如何关闭ssh登录

小樊
43
2026-10-17 09:07:28
栏目: 智能运维

在 CentOS 中“关闭 SSH 登录”有多种理解,下面按常见场景分别说明,你可以按需选择。


一、彻底关闭 SSH 服务(禁止所有人通过 SSH 登录)

CentOS 6(SysVinit)

service sshd stop
chkconfig sshd off

CentOS 7 / 8 / Stream(systemd)

systemctl stop sshd
systemctl disable sshd

⚠️ 注意:如果你是通过 SSH 远程连接的,执行后你会立即断开且无法再连上,请确保有其它管理方式(如控制台、IPMI)。


二、只允许特定用户/禁止某些用户 SSH 登录

1️⃣ 禁止 root 登录(最常见)

编辑配置文件:

vi /etc/ssh/sshd_config

修改:

PermitRootLogin no

重启服务:

systemctl restart sshd

2️⃣ 禁止指定用户 SSH 登录

在 sshd_config 中添加:

DenyUsers user1 user2

或只允许某些用户:

AllowUsers alice bob

然后重启:

systemctl restart sshd

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

使用 firewalld

# 查看
firewall-cmd --list-services

# 移除 ssh
firewall-cmd --permanent --remove-service=ssh
firewall-cmd --reload

使用 iptables(老系统)

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

四、临时禁止 SSH 登录(维护模式)

systemctl stop sshd

需要时再:

systemctl start sshd

五、完全禁止 SSH 登录但保留服务(拒绝所有连接)

在 sshd_config 中:

AllowUsers none

或

DenyUsers *

然后:

systemctl restart sshd

✅ 推荐做法(安全建议)

  • 生产环境:不要彻底关闭 SSH
  • 建议:
    • 禁止 root 登录
    • 使用密钥登录
    • 修改默认端口
    • 使用防火墙限制 IP

如果你能说明是 临时 / 永久 / 禁止某个用户 / 云服务器,我可以给你更精确的操作命令。

0 踩