iptables persistence under CentOS

Keywords: Linux iptables firewall vim

iptables rule persistence

  • Set firewall rules

    iptables -A INPUT -s 1.1.1.1/32 -p tcp -m tcp --dport 22 -j DROP 
    iptables -A INPUT -s 2.2.2.2/32 -p tcp -m tcp --dport 22 -j DROP 
    iptables -A INPUT -s 3.3.3.3/32 -p tcp -m tcp --dport 22 -j DROP 
    iptables -A INPUT -s 4.4.4.4/32 -p tcp -m tcp --dport 22 -j DROP
  • Save firewall rules

    service iptables save
    //or
    iptables-save > /etc/sysconfig/iptables
  • Set iptables rules for automatic recovery after power on

    vim /etc/rc.d/rc.local
    iptables-restore < /etc/sysconfig/iptables

iptables shutdown auto save

  • Clear firewall rules first

    iptables -F
  • Save the iptables rule, that is, empty the / etc/sysconfig/iptables file

    service iptables save
    //or
    iptables-save > /etc/sysconfig/iptables
  • Manually generate some iptables rules

    iptables -A INPUT -s 1.1.1.1/32 -p tcp -m tcp --dport 22 -j DROP 
    iptables -A INPUT -s 2.2.2.2/32 -p tcp -m tcp --dport 22 -j DROP 
    iptables -A INPUT -s 3.3.3.3/32 -p tcp -m tcp --dport 22 -j DROP 
    iptables -A INPUT -s 4.4.4.4/32 -p tcp -m tcp --dport 22 -j DROP
  • Check whether the iptables rule is effective

    [root@ecs-7740 init.d]# iptables -nvL
    Chain INPUT (policy ACCEPT 27 packets, 1978 bytes)
     pkts bytes target     prot opt in     out     source               destination         
    0     0 DROP       tcp  --  *      *       1.1.1.1              0.0.0.0/0           tcp dpt:22 
    0     0 DROP       tcp  --  *      *       2.2.2.2              0.0.0.0/0           tcp dpt:22 
    0     0 DROP       tcp  --  *      *       3.3.3.3              0.0.0.0/0           tcp dpt:22 
    0     0 DROP       tcp  --  *      *       4.4.4.4              0.0.0.0/0           tcp dpt:22 
  • Set the iptables rule to save automatically when shutting down
    Create a script to execute when shutting down and make sure it has execute permission

    vim /etc/init.d/shutdownsh
    iptables-save > /etc/sysconfig/iptables
    chmod +x /etc/sysconfig/shutdownsh 
    ls /etc/sysconfig/shutdownsh 
    -rwxr-xr-x 1 root root 40 Jan 16 22:05 shutdownsh
  • Create a soft connection file to rcN.d, where N is the operation level
    http://blog.csdn.net/snaking616/article/details/78680021
    https://wenku.baidu.com/view/9a988bb9f424ccbff121dd36a32d7375a417c6f1.html

    ln -s /etc/init.d/shutdownsh /etc/rc6.d/K01shutdownsh 
    ln -s /etc/init.d/shutdownsh /etc/rc0.d/K01shutdownsh 
    ln -s /etc/init.d/shutdownsh /var/lock/subsys/

    Note: the above method (creating an empty file or soft connection in / var/lock/subusys is only effective in the first shutdown or restart, and the file under / var/lock/subsys will disappear automatically after the restart, so the script cannot be executed in the second shutdown or restart)

Posted by TechGuru on Sun, 03 May 2020 22:15:49 -0700