I am new to bash scripting have patience.
I have this code where it scans ports of domains and shows them to the user and it works perfectly by it self but when i added functions to it gives me errors. What am I doing wrong here?
check_parms () {
case $# in
1) ports='1-1023'
host=$1 ;;
2) ports=$1
host=$2 ;;
*) echo 'Usage: portscan [port|range] host'
exit 1 ;;
esac
}
# check port range
check_ports () {
if [ "$(echo $ports | grep '^[1-9][0-9]*-[1-9][0-9]*$')" != "" ]; then
firstport=$(echo $ports | cut -d- -f1)
lastport=$(echo $ports | cut -d- -f2)
elif [ "$(echo $ports | grep '^[1-9][0-9]*$')" != "" ]; then
firstport=$ports
lastport=$ports
else
echo "$ports is an invalid port(s) value"
exit 2
fi
}
# check firstport > lastport
check_order () {
if [ $firstport -gt $lastport ]; then
echo $firstport is larger than $lastport
exit 3
fi
}
# check host value
check_host () {
regex='^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$'
if [ "$(echo $host | grep '[A-Za-z]')" != "" ]; then
response=$(host $host)
if [[ "$response" =~ "timed out" || "$response" =~ "not found" ]]; then
echo host $host not found
exit 4
fi
elif [[ ! $host =~ $regex ]]; then
echo $host is an invalid host address
exit 5
fi
}
# check if host is reachable using ping
check_ping () {
if [[ "$(ping -c 1 -W 2 -n $host)" =~ "0 received" ]]; then
echo $host is unreachable
exit 6
fi
}
# start the scan
do_scan () {
echo -n "Scanning "
for p in $(seq $firstport $lastport)
do
echo -n .
x=$((echo >/dev/tcp/$host/$p) >/dev/null 2>&1 && echo "$p open")
if [ "$x" != "" ]; then
y="${y}
$x"
fi
done
}
# show results of scan
show_results () {
echo -e "\n$y\n"
exit 0
}
check_parms $#
check_ports $ports
check_order $firstport $lastport
check_host $host
check_ping $host
do_scan $host $firstport $lastport
show_results
set -x
to trace each command run and see where things first go wrong is a good place to start with that. See also sscce.org and stackoverflow.com/help/mcveportscan host port
. This would also coincidentally simplify the code, and also it is then trivial to adapt it to accept multiple discrete ports or ranges.