I found a script that allows you to open or close any port and save it to the iptables. The problem I am having is it throws a syntax error after I tell it to close, but before I can give it a port number. The issue is right before the first else.
#!/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin
clear
echo -e "############################nnnPresent ports opened on this machine are
$(iptables -nL INPUT | grep ACCEPT | grep dpt)
nCompleted listing...nnn#########################"
read -p "To open port enter open, to close etner close) " OPT1
if [[ "$OPT1" == open ]]
then
read -p "Please enter your desired port number to open: " PORT1
if [[ "$PORT1" =~ [0-9]{1,6} ]]
then
iptables -D INPUT $(iptables -nL INPUT --line-numbers | grep "$PORT1" | grep REJECT | awk '{print $1}')
iptables -A INPUT -m tcp -p tcp --dport "$PORT1" -j ACCEPT && { service iptables save;service iptables restart; echo -e "Ports opend through iptables are n$(iptables -nL INPUT | grep ACCEPT | grep dpt)"; }
else
echo "Please enter a valid port(0-65000)"
fi
elif [[ "$OPT1" == close ]]
then
read -p "Please enter your desired port number to close: " PORT1
if [[ "$PORT1" =~ [0-9]{1,6} ]]
then
iptables -D INPUT $(iptables -nL INPUT --line-numbers | grep "$PORT1" | grep ACCEPT | awk '{print $1}')
iptables -A INPUT -m tcp -p tcp --dport "$PORT1" -j REJECT && { service iptables save;service iptables restart; echo -e "Ports closed through iptables are n$(iptables -nL INPUT | grep REJECT | grep dpt)"; }
else
echo "Please enter a valid port(0-65000)"
fi
else
echo "Please enter only open or close..! Exiting script now";exit 1
fi
I don't see any error in the script. Can you paste the error that you are getting? See below
[root@kali ~]# ./ip.sh
######################nnnPresent ports opened on this machine arenCompleted listing...nnn#########################
To open port enter open, to close etner close) close
Please enter your desired port number to close: 23
iptables: Bad rule (does a matching rule exist in that chain?).
iptables: Saving firewall rules to /etc/sysconfig/iptables:[ OK ]
Redirecting to /bin/systemctl restart iptables.service
Ports closed through iptables are nREJECT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:23 reject-with icmp-port-unreachable