Using kernel 2.6.x
Note: In a previous question, I tried to accomplish this with a bash array. On this OS, non-sh shells are installed as Entware-NG packages and can't be used since they load after the script runs.
Goal: Script the creation of iptables rules using sh (not bash, zsh, etc.) with the following format. For each interface in $NAME ...
- Create a rule for it's source network IP address from the corresponding position in $NETID. The first value in $NAME has a source network address built from the first value in $NETID. For example, -i eth1 corresponds with -src 192.168.10.0/24 and -i eth2 corresponds with 192.168.20.0/24.
- Build the destination IP address for the values in $NETID not used in the source network address. For example, -src 192.168.10.0/24 -dst 192.168.20.0/24.
- Build each rule with one destination network address. Do not specify multiple addresses for the -dst value.
Desired Result:
iptables -I FORWARD -i eth1 -src 192.168.10.0/24 -dst 192.168.20.0/24
iptables -I FORWARD -i eth1 -src 192.168.10.0/24 -dst 192.168.30.0/24
iptables -I FORWARD -i eth2 -src 192.168.20.0/24 -dst 192.168.10.0/24
iptables -I FORWARD -i eth2 -src 192.168.20.0/24 -dst 192.168.30.0/24
iptables -I FORWARD -i eth3 -src 192.168.30.0/24 -dst 192.168.10.0/24
iptables -I FORWARD -i eth3 -src 192.168.30.0/24 -dst 192.168.20.0/24
Problem: The script below does not create a 1:1 relationship with the interface name and -src value. For example, eth1 and 192.168.10.0/24, eth2 and 192.168.20.0/24, etc.
#!/bin/sh
NETID="10 20 30"
NAME="eth1 eth2 eth3"
for i in $NETID; do
sarg="192.168.$i.0/24"
darg=""
for j in $NETID; do
[ "$i" -eq "$j" ] && continue
darg="192.168.$j.0/24"
for k in $NAME; do
echo "iptables -I FORWARD -i $k -s $sarg -d $darg -j DROP"
done
done
done
-eq
is for numerical comparisons. Use=
instead.[ "$i" = "$j" ] && continue
– Wildcard Sep 8 '17 at 2:01NAME
tosrc
? (You don't.) That code won't ever get your desired result. – Wildcard Sep 8 '17 at 2:06NAME=([10]=eth1 [20]=eth2 [30]=eth3)
and${NAME[$NETID]}
? – xhienne Sep 8 '17 at 13:46sh
is what I call a Posix shell. My summary is to avoid misled answers. What you want to achieve is get the name from the netid, that is the equivalent of${NAME[$NETID]}
, but with a meresh
. – xhienne Sep 8 '17 at 14:09