温馨提示×

如何在CentOS上配置SSH防火墙规则

小樊
57
2025-06-12 05:01:13
栏目: 智能运维

在CentOS上配置SSH防火墙规则,通常涉及使用firewalldiptables。以下是使用这两种方法的详细步骤:

使用 firewalld

  1. 启动并启用 firewalld 服务

    sudo systemctl start firewalld
    sudo systemctl enable firewalld
    
  2. 允许SSH连接

    sudo firewall-cmd --permanent --add-service=ssh
    
  3. 重新加载防火墙规则

    sudo firewall-cmd --reload
    
  4. 验证SSH端口是否开放

    sudo firewall-cmd --list-all
    

    你应该能看到类似以下的输出,表明SSH端口(默认是22)已经开放:

    services: ssh
    ports: 22/tcp
    

使用 iptables

  1. 允许SSH连接

    sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
    
  2. 保存 iptables 规则: CentOS 7及以上版本使用 firewalld,但如果你使用的是CentOS 6或其他不支持 firewalld 的版本,可以使用以下命令保存规则:

    sudo service iptables save
    
  3. 重启 iptables 服务

    sudo service iptables restart
    
  4. 验证SSH端口是否开放

    sudo iptables -L -n | grep 22
    

    你应该能看到类似以下的输出,表明SSH端口(默认是22)已经开放:

    ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh
    

其他安全建议

  • 更改默认SSH端口:为了增加安全性,可以考虑更改SSH的默认端口(22)。编辑 /etc/ssh/sshd_config 文件,找到 Port 行并修改为你选择的端口号,然后重启SSH服务:

    sudo systemctl restart sshd
    
  • 限制SSH访问:可以通过编辑 /etc/hosts.deny/etc/hosts.allow 文件来限制SSH访问。例如,只允许特定IP地址访问SSH:

    sudo echo "sshd: 192.168.1.1" >> /etc/hosts.deny
    sudo echo "sshd: 192.168.1.2" >> /etc/hosts.allow
    
  • 使用密钥认证:为了进一步提高安全性,建议使用SSH密钥认证而不是密码认证。生成密钥对并将其添加到远程服务器的 ~/.ssh/authorized_keys 文件中。

通过以上步骤,你可以在CentOS上配置SSH防火墙规则,并采取其他安全措施来保护你的SSH服务。

0