我在这个博客中找到了一个非常有用的脚本,它可以为特定主机动态创建规则。该脚本需要使用 cron 运行,因此它可以查找主机名并添加/删除规则,以防 IP 更改。
#!/bin/bash
HOSTS_ALLOW=/etc/ufw-dynamic-hosts.allow
IPS_ALLOW=/var/tmp/ufw-dynamic-ips.allow
add_rule() {
local proto=$1
local port=$2
local ip=$3
local regex="${port}\/${proto}.*ALLOW.*IN.*${ip}"
local rule=$(ufw status numbered | grep $regex)
if [ -z "$rule" ]; then
ufw allow proto ${proto} from ${ip} to any port ${port}
else
echo "rule already exists. nothing to do."
fi
}
delete_rule() {
local proto=$1
local port=$2
local ip=$3
local regex="${port}\/${proto}.*ALLOW.*IN.*${ip}"
local rule=$(ufw status numbered | grep $regex)
if [ -n "$rule" ]; then
ufw delete allow proto ${proto} from ${ip} to any port ${port}
else
echo "rule does not exist. nothing to do."
fi
}
sed '/^[[:space:]]*$/d' ${HOSTS_ALLOW} | sed '/^[[:space:]]*#/d' | while read line
do
proto=$(echo ${line} | cut -d: -f1)
port=$(echo ${line} | cut -d: -f2)
host=$(echo ${line} | cut -d: -f3)
if [ -f ${IPS_ALLOW} ]; then
old_ip=$(cat ${IPS_ALLOW} | grep ${host} | cut -d: -f2)
fi
ip=$(dig +short $host | tail -n 1)
if [ -z ${ip} ]; then
if [ -n "${old_ip}" ]; then
delete_rule $proto $port $old_ip
fi
echo "Failed to resolve the ip address of ${host}." 1>&2
exit 1
fi
if [ -n "${old_ip}" ]; then
if [ ${ip} != ${old_ip} ]; then
delete_rule $proto $port $old_ip
fi
fi
add_rule $proto $port $ip
if [ -f ${IPS_ALLOW} ]; then
sed -i.bak /^${host}*/d ${IPS_ALLOW}
fi
echo "${host}:${ip}" >> ${IPS_ALLOW}
done
Run Code Online (Sandbox Code Playgroud)
的内容/etc/ufw-dynamic-hosts.allow可能如下所示:
tcp:22:yourpc.no-ip.org
Run Code Online (Sandbox Code Playgroud)
每五分钟执行一次脚本的 crontab 条目可能如下所示:
*/5 * * * * /usr/local/sbin/ufw-dynamic-host-update > /dev/null
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4954 次 |
| 最近记录: |