温馨提示×

centos iptables如何设置超时时间

小樊
45
2025-10-17 09:34:00
栏目: 智能运维

在 CentOS 系统中,使用 iptables 设置连接超时时间可以通过设置 conntrack 超时来实现。以下是一些常用的命令示例:

  1. 查看当前的 conntrack 超时设置

    sudo iptables -L -n -v | grep conntrack
    
  2. 设置特定协议的连接超时时间

    • TCP 连接超时

      sudo iptables -A INPUT -p tcp --syn -m conntrack --ctstate NEW -m timeout --timeout 300s -j ACCEPT
      

      这条命令将新的 TCP 连接的超时时间设置为 300 秒。

    • UDP 连接超时

      sudo iptables -A INPUT -p udp -m conntrack --ctstate NEW -m timeout --timeout 300s -j ACCEPT
      

      这条命令将新的 UDP 连接的超时时间设置为 300 秒。

    • ICMP 连接超时

      sudo iptables -A INPUT -p icmp -m conntrack --ctstate NEW -m timeout --timeout 300s -j ACCEPT
      

      这条命令将新的 ICMP 连接的超时时间设置为 300 秒。

  3. 设置所有连接的默认超时时间

    sudo iptables -t raw -A PREROUTING -m conntrack --ctstate INVALID -j DROP
    sudo iptables -t raw -A PREROUTING -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN
    sudo iptables -t raw -A PREROUTING -m conntrack --ctstate NEW -m timeout --timeout 300s -j LOG --log-prefix "NEW CONN: "
    
  4. 保存 iptables 规则: 在 CentOS 7 及以上版本中,可以使用 firewall-cmd 来管理防火墙规则,并保存规则:

    sudo firewall-cmd --runtime-to-permanent
    

    在 CentOS 6 中,可以使用 service iptables save 命令来保存规则:

    sudo service iptables save
    

请注意,修改 iptables 规则可能会影响系统的安全性和网络连接,因此在执行这些命令之前,请确保你了解这些命令的作用,并在必要时备份当前的规则。

0