3

Hi I've created a script to setup Nagios on my remote servers. My script checks iptables to see if a firewall rule already exists and then is supposed to add the rule if it's not already there.

Right now the script just echoes out the rule but it's not actually able to write it any help would be greatly appreciated.

ssh -t -t root@$serverName << EOF
  service nrpe restart
  chkconfig nrpe on
  if [ "cat /etc/sysconfig/iptables | grep -- "5666"" != "-A INPUT -p tcp -m tcp --dport 5666 -j ACCEPT" ] ; then echo "iptables -I INPUT -s 0/0 -p tcp --dport 5666 -j ACCEPT" ; fi
  service iptables save
  exit
EOF

2 Answers 2

4

Check if rules exists, and if not, add it:

iptables -C INPUT -s 0/0 -p tcp --dport 5666 -j ACCEPT || iptables -I INPUT -s 0/0 -p tcp --dport 5666 -j ACCEPT
0

You just have to change

echo "iptables -I INPUT -s 0/0 -p tcp --dport 5666 -j ACCEPT"

to

iptables -I INPUT -s 0/0 -p tcp --dport 5666 -j ACCEPT

You can leave -s 0/0 out:

iptables -I INPUT -p tcp --dport 5666 -j ACCEPT

And it would make sense to consider what is the best position within INPUT. If this rule should be the fifth (instead of the first) then change the call to:

iptables -I 5 INPUT -p tcp --dport 5666 -j ACCEPT

And

"cat /etc/sysconfig/iptables | grep -- "5666""

contains an error. The command

cat /etc/sysconfig/iptables | grep -- "5666"

is not executed. You must add command substitution:

"$(cat /etc/sysconfig/iptables | grep -- "5666")"
2
  • Still not quite there I'm now getting "grep: /etc/sysconfig/iptables: No such file or directory". I've changed my code to be ` if [ "$(grep 5666 /etc/sysconfig/iptables)" != "-A INPUT -p tcp -m tcp --dport 5666 -j ACC EPT" ] ; then iptables -I INPUT 3 -p tcp --dport 5666 -j ACCEPT ; fi`
    – bpal
    May 8, 2014 at 19:15
  • @bpal If a file doesn't exist then you can trivially not use it as a source for the data to be checked. You need iptables -L INPUT -nv | grep ... (and would have to adapt the grep search string) or (better): iptables -C INPUT -s 0/0 -p tcp --dport 5666 -j ACCEPT May 11, 2014 at 14:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .