Automated firewall releases target domain name IP

#!/bin/bash
# 设置要获取IP地址的域名
domain="yourdomain.com"

# 获取域名的IP地址
new_ip=$(dig +short A $domain)

# 移除之前添加放行的IP地址(通过备注找它的编号)
rule_number=$(iptables -L INPUT -n --line-numbers -v | awk -v domain="${domain}" '$0 ~ "Allow from " domain {print $1}')

# 如果有就删除
if [ -n "$rule_number" ]; then
    iptables -D INPUT $rule_number
fi

# 添加新的IP地址到iptables规则(带备注)
iptables -A INPUT -s $new_ip -m comment --comment "Allow from $domain" -j ACCEPT

#保存规则,如果有docker请省略这一步
service iptables save

Explanation of the regular expression part:

  • Allow from: This is a fixed text string that represents the beginning of the comment content in the rule.
  • domain: This is a variable that stores the content of the annotation you want to match. Use the -v option in the command to pass this variable to the awk command.
  • ~Operator: In awk, the ~operator is used for pattern matching.
  • $0: This is a special variable in awk that represents the entire input line.
  • ~The part after the operator "Allow from" domain is our pattern. It instructs awk to look for the part of the input line that begins with "Allow from
    ", followed by the contents of the domain variable.

Therefore, using the pattern "Allow from" domain, we can match rule lines that contain the desired annotation. Once a matching line is found, print $1 will print the first field of that line, which is the rule line number.

Why is it not saved with docker:

When using Docker, iptables rules are automatically managed by Docker. Docker uses its own network bridging and forwarding mechanism to manage communication between containers, and it automatically updates iptables rules to adapt to the container's network needs.

When you run the service iptables save command, it will try to save the current system's iptables rules into the configuration file, but this command will not take into account the rules managed by Docker.

If you want to save the iptables rules managed by Docker, you can use the command that comes with Docker. For example, use the docker save command to save Docker's iptables rules to a file, and then use the docker load command to reload the rules when needed.

In addition, starting from Docker version 1.13, Docker has introduced new commands docker save and docker load for saving and loading the state of the container, including network rule. This way you can use the docker save command to save Docker's state, and use the docker load command to reload the state, including iptables rules, when needed.

In short, if you are using Docker and want to save iptables rules, it is recommended to use the relevant commands provided by Docker to manage and save the rules.

Guess you like

Origin blog.csdn.net/weixin_43576565/article/details/132659474