【发布时间】:2021-01-29 06:20:29
【问题描述】:
嗨,我最近开始学习 bash 脚本,因为我很“绿色”,可以这么说,我希望能得到一些帮助。我有这个问题,我似乎无法自己解决。我希望这个程序通读每一行以检查给定 IP 地址是否有任何 iptables 规则。如果有:取行号,然后用 iptables -R INPUT $lineNumberHere -s $IP_ADDRESS -j $newPolicy 修改或删除。
但是程序开始读取第一行并将行号注册为“Chain”和“num”,这会导致错误。有没有绕过这两行的方法?
只是为了澄清。我正在以 root 身份运行程序
# The IP address is listen in rules
# Find the line number of the rule
echo ""
echo "The IP allready has a rule in iptables"
iptables -L INPUT --line-numbers | while read line; do
echo ""
echo "Checking line: $line"
LINE_NUMBER=$(($line | cut -d " " -f1))
BANNED_IP=$(($line | cut -d " " -f4 | cut -d "/" -f1))
re='^[0-9]+$'
if [[ "$LINE_NUMBER" =~ $re ]]; then
echo "Line nr. $LINE_NUMBER"
if [ "$IP_ADDRESS"="$BANNED_IP" ]; then
echo "Changing status to BANNED"
iptables -R INPUT "$LINE_NUMBER" -s "$IP_ADDRESS" -j DROP
fi
else
echo "error: Not a number" >&2
continue;
fi
done
【问题讨论】:
标签: linux bash shell ssh iptables