打开/关闭端口shell脚本

时间:2015-12-12 13:56:35

标签: bash shell scripting port iptables

我找到了一个脚本,允许您打开或关闭任何端口并将其保存到iptables。我遇到的问题是它告诉它关闭后抛出语法错误,但在我给它一个端口号之前。问题就在第一个问题之前。

#!/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

1 个答案:

答案 0 :(得分:0)

我没有在脚本中看到任何错误。你能粘贴你得到的错误吗?见下文

[root @ kali~]#。/ ip.sh

######################在此机器上打开的nnnPresent端口是

n完成列表... nnn #########################

打开端口输入open,关闭etner close)关闭

请输入您想要关闭的端口号:23

iptables:错误规则(该链中是否存在匹配规则?)。

iptables:将防火墙规则保存到/ etc / sysconfig / iptables:[确定]

重定向到/ bin / systemctl重新启动iptables.service

通过iptables关闭的端口是nREJECT tcp - 0.0.0.0/0 0.0.0.0/0 tcp dpt:23 reject-with icmp-port-unreachable