Open/close port shell script - bash

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 are
nCompleted 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

Related

netcat - How do I synchronize my portscan and port listen scripts and how do i export all output to a .txt file?

My goal is to have a port listen script on Host A which listens on predefined ports using netcat.
While this script listens, the port scan script is running on Host B and checks if the ports on Host A or open or not.
The output of the scan script needs to be directed to a separate .txt file and must include all information from the nc -zvv output.
The listen script looks like this:
#!/bin/bash
# Define the four arrays of ports to listen on
ports_1st=(20 21 22 80 443)
ports_2nd=(2000 2001 2002 2003)
ports_3rd=(3000 3001 3002 3003)
ports_4th=(4000 4001 4002 4003)
# Sleep to allow the scan script to start and bind to all ports
echo "Start PortScan.sh as soon as port listen starts!"
sleep 5
echo -e "\n"
echo -e "\n"
# Countdown timer
echo "Start the port scan in:"
for i in 5 4 3 2 1; do
echo "$i..."
sleep 1
done
# Loop through each array of ports and use nc to listen on each port
echo "Listening on 1st ports..."
for ports in ports_1st; do
for port in "${!ports[#]}"; do
nc -l -k -p $port &
done
done
echo -e "\n"
echo "Listening on 1st ports completed"
echo -e "\n"
echo -e "\n"
echo "Listening on 2nd ports..."
for ports in ports_2nd; do
for port in "${!ports[#]}"; do
nc -l -k -p $port &
done
done
echo -e "\n"
echo "Listening on 2nd ports completed"
echo -e "\n"
echo -e "\n"
echo "Listening on 3rd ports..."
for ports in ports_3rd; do
for port in "${!ports[#]}"; do
nc -l -k -p $port &
done
done
echo -e "\n"
echo "Listening on 3rd ports completed"
echo -e "\n"
echo -e "\n"
echo "Listening on 4th ports..."
for ports in ports_4th; do
for port in "${!ports[#]}"; do
nc -l -k -p $port &
done
done
echo -e "\n"
echo "Listening on 4th ports completed"
echo -e "\n"
echo -e "\n"
# Wait for all background nc processes to complete
wait
echo "Portscan has been completed"
echo -e "\n"
echo -e "\n"
And the scanscript looks like this:
#!/bin/bash
# Define the range of ports to scan
ports_1st=(20 21 22 80 443)
ports_2nd=(2000 2001 2002 2003)
ports_3rd=(3000 3001 3002 3003)
ports_4th=(4000 4001 4002 4003)
# Define the IP of the target host
echo "Please enter the server IP of the target host!"
read target_host
echo -e "\n"
echo -e "\n"
# Define current date variable
current_date=$(date +"%Y-%m-%d")
# Loop through the range of ports and use nc to test for a response
echo "Scanning 1st ports..."
for ports in ports_1st; do
for port in "${ports[#]}"; do
nc -zvv -w 1 $target_host $port 2>&1 | tee -a Portscan_$current_date.txt
if [ $? -eq 0 ]; then
echo "Port $port is open" | tee -a Portscan_$current_date.txt
else
echo "Port $port is closed or connection timed out" | tee -a Portscan_$current_date.txt
fi
done
echo "1st port scan completed" | tee -a Portscan_$current_date.txt
echo -e "\n"
echo -e "\n"
echo "Scanning 2nd ports..."
for ports in ports_2nd; do
for port in "${ports[#]}"; do
nc -zvv -w 1 $target_host $port 2>&1 | tee -a Portscan_$current_date.txt
if [ $? -eq 0 ]; then
echo "Port $port is open" | tee -a Portscan_$current_date.txt
else
echo "Port $port is closed or connection timed out" | tee -a Portscan_$current_date.txt
fi
done
echo "2nd scan completed" | tee -a Portscan_$current_date.txt
echo -e "\n"
echo -e "\n"
echo "Scanning 3rd ports..."
for ports in ports_3rd; do
for port in "${ports[#]}"; do
nc -zvv -w 1 $target_host $port 2>&1 | tee -a Portscan_$current_date.txt
if [ $? -eq 0 ]; then
echo "Port $port is open" | tee -a Portscan_$current_date.txt
else
echo "Port $port is closed or connection timed out" | tee -a Portscan_$current_date.txt
fi
done
echo "3rd port scan completed" | tee -a Portscan_$current_date.txt
echo -e "\n"
echo -e "\n"
echo "Scanning 4th ports..."
for ports in ports_4th; do
for port in "${ports[#]}"; do
nc -zvv -w 1 $target_host $port 2>&1 | tee -a Portscan_$current_date.txt
if [ $? -eq 0 ]; then
echo "Port $port is open" | tee -a Portscan_$current_date.txt
else
echo "Port $port is closed or connection timed out" | tee -a Portscan_$current_date.txt
fi
done
echo "4th port scan completed" | tee -a Portscan_$current_date.txt
echo -e "\n"
echo -e "\n"
done
done
done
done
The problem is that the listen script seems to end instantly instead of waiting for all ports to be scanned and the portscan script does not put the proper output to the .txt file.
Do you have any ideas on how to fix this?
Side notes:
Netcat is mandatory to be used.
I am expecting to loop through each port mentioned in the listen script as well as in the scan script.
The scan script is supposed to prompt if the port is open or closed/timeout in a .txt file.

Extracting specific nmap output in bash

I'm getting following nmap output from a scan:
PORT STATE SERVICE
113/tcp closed ident
443/tcp open https
5060/tcp open sip
I want to extract only open ports and save them into a variable while my script progress is below:
#!/bin/bash
echo Please enter your IP/domain address for nmap vulnerability scanning:
read IP
echo Your results against $ip will be output in sometime
nmap -sS -oG output.txt $ip
Grep them
nmap -sS -oG output.txt $ip | grep open
To store in var
open_ports=$(nmap -sS -oG output.txt $ip | grep open)
open_ports=${open_ports//[^0-9]/ } # remove text
Convert to an array
open_ports_arr=( $open_ports )
Here is how you can filter and extract open ports using awk and read the results into a bash array:
#!/usr/bin/env bash
# Read prompt ip address
read \
-p 'Please enter your IP/domain address for nmap vulnerability scanning: ' \
-r ip
# Print format info to user
printf 'Your results against %s will be output in sometime.\n' "$ip"
# Read the output of the nmap | awk commands into the ports array
IFS=$'\n' read -r -d '' -a ports < <(
# Pipe the result of nmap to awk for processing
nmap -sS -oG output.txt "$ip" |
awk -F'/' '
/[[:space:]]+open[[:space:]]+/{
p[$1]++
}
END{
for (k in p)
print k
}'
)
# If the resulting pors array is not empty iterate print format its content
if [ ${#ports[#]} -gt 0 ]; then
printf 'List of open ports on host IP: %s\n' "$ip"
for p in "${ports[#]}"; do
printf '%d\n' "$p"
done
fi

Telnet to one computer from multiple computer

I have scenario where I have list of 100s of server . Want to check whether those all server can reach to specified destination server or not by telneting from all server to that destination server.
I have written a code as below,
#!/bin/bash
#bash to check telnet status.
#set -x;
#
#clear
SetParam() {
export URLFILE="Host_PortFile.txt"
export TIME=`date +%d-%m-%Y_%H.%M.%S`
export port=80
export STATUS_UP=`echo -e "\E[32m[ RUNNING ]\E[0m"`
export STATUS_DOWN=`echo -e "\E[31m[ DOWN ]\E[0m"`
export MAIL_TO="admin(at)techpaste(dot)com"
export SHELL_LOG="`basename $0`.log"
}
Telnet_Status() {
SetParam
cat $URLFILE | while read next
do
server=`echo $next | cut -d : -f1`
port=`echo $next | awk -F":" '{print $2}'`
TELNETCOUNT=`sleep 5 | telnet $server $port | grep -v "Connection refused" | grep "Connected to" | grep -v grep | wc -l`
if [ $TELNETCOUNT -eq 1 ] ; then
echo -e "$TIME : Port $port of URL http://$server:$port/ is \E[32m[ OPEN ]\E[0m";
else
echo -e "$TIME : Port $port of URL http://$server:$port/ is \E[31m[ NOT OPEN ]\E[0m";
echo -e "$TIME : Port $port of URL http://$server:$port/ is NOT OPEN" | mailx -s "Port $port of URL $server:$port/ is DOWN!!!" $MAIL_TO;
fi
done;
}
Main() {
Telnet_Status
}
SetParam
Main | tee -a $SHELL_LOG
My Host_PortFile.txt file looks like,
gmail.com:443
But here, i need to go to individual server and has to run this which consumes more time. Is there any modification I can do so that I can run the script from one machine to read all source server name from text file or any and can check that server can reach the destination server or not? Can anyone suggest on this please?

DD-WRT Bash script at startup issue

Hey all I have the following BASH script running at startup on my WRT1900ac linksys:
USER="admin"
PASS="passhere"
PROTOCOL="http"
ROUTER_IP="192.168.1.1"
# Port to connect to which will provide the JSON data.
PORT=9898
while [ 1 ]
do
# Grab connected device MAC addresses through router status page.
MACS=$(curl -s --user $USER:$PASS $PROTOCOL://$ROUTER_IP/Status_Wireless.live.asp)
# clear temp JSON file
echo > temp.log
# Get hostname and IP (just in case there is no hostname).
for MAC in $(echo $MACS | grep -oE "wl_mac::[a-z0-9]{2}:[a-z0-9]{2}:[a-z0-9]{2}:[a-z0-9]{2}:[a-z0-9]{2}:[a-z0-9]{2}" | cut -c 9-);
do
grep 0x /proc/net/arp | awk '{print $1 " " $4}' | while IFS= read -r line
do
IP=$(echo $line | cut -d' ' -f1)
MACTEMP=$(echo $line | cut -d' ' -f2)
HOST=$(arp -a | grep $IP | cut -d' ' -f1)
# if no hostname exists, just use IP.
if [ "$HOST" == "" ]
then
HOST=$IP
fi
if [ "$MAC" == "$MACTEMP" ]
then
JSON="{'hostname' : '$HOST', 'mac_address' : '$MAC'}"
echo $JSON >> temp.log
fi
done
done
# Provide the JSON formatted output on $PORT of router.
# This allows one connection before closing the port (connect, receive data, close).
# Port will reopen every 5 minutes with new data as setup in a cron job.
echo -e "HTTP/1.1 200 OK\n\n $(cat temp.log)" | nc -l -p$PORT >/dev/null
# Wait for 10 seconds and do it all over.
sleep 10
done
And for some reason when I reboot the router and then try to visit http://192.168.1.1:9898 it just shows a blank page even though I have my android cell phone connected via wifi to the router and the router shows the MAC address on the status page.
What should be on that page is all the wireless MAC address that are currently connected to the router and displaying them out in JSON form.
Any BASH guru's here that can help spot the problem?
I think it should be
echo -e "HTTP/1.1 200 OK\n\n $(cat temp.log)" | nc -l -p$PORT 0.0.0.0 >/dev/null

iptable Bad argument `ACCEPT'

I am trygin the following..
#!/bin/bash
NOIPHOST=example.noip.me
LOGFILE=iptables_update.log
Current_IP=$(host $NOIPHOST | cut -f4 -d' ')
if [ $LOGFILE = "" ] ; then
/sbin/iptables -I INPUT -m tcp -p tcp -s $Current_IP -j ACCEPT
echo $Current_IP > $LOGFILE
else
Last_IP=$(cat $LOGFILE)
if [ "$Current_IP" = "$Last_IP" ] ; then
echo IP address has not changed
else
/sbin/iptables -D INPUT -m tcp -p tcp -s $Last_IP -j ACCEPT
/sbin/iptables -I INPUT -m tcp -p tcp -s $Current_IP -j ACCEPT
iptables-persistent save
echo $Current_IP > $LOGFILE
echo iptables have been updated
fi
fi
I am getting this error..
Bad argument ACCEPT' Tryiptables -h' or 'iptables --help' for more
information. iptables have been updated
I have also tried using these..
iptables -D INPUT -m tcp -p tcp -s $Last_IP -j ACCEPT
iptables -I INPUT -m tcp -p tcp -s $Current_IP -j ACCEPT
but still same error.
Anyway to fix this?
Are you sure you don't have any newlines in your $Last_IP variable?
Can you try adding the following before your iptables -D... line?
Last_IP=$(echo $Last_IP|tr -d '\n')

Resources