Lab 2.1: Port Scanning 1

Summary:

During this lab we worked on understanding nmap more and mad a custom script to take in a list of hosts and ports then use /dev/tcp/$host/$port to see if the ports are open.

Port Scanner Program:

Code:

#!/bin/bash

# Make sure 
if [[ -z $1 && -z $2 ]] ; then
    echo "No host or port file supplied"
    exit 1
elif [[ -z $1 ]] ; then
    echo "No host file supplied"
    exit 1
elif [[ -z $2 ]] ; then
    echo "No port file supplied"
    exit 1
fi

# Take in files
hostfile=$1
portfile=$2

# if var 3 is 1 then the program will run verbose
if [[ $3 -eq 1 ]]; then

# Making sure files are formatted properly 
  echo "-- Host file format check --"
  for host in $(cat $hostfile); do
    if [[ $host =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
      echo "$host is formated properly"
    else
      echo "$host is not the correct format"
    fi
  done

  echo ""

  echo "-- Port file format check --"
  for port in $(cat $portfile); do
    if [[ $port =~ ^(0|6[0-5][0-5][0-3][0-5]|[1-5][0-9][0-9][0-9][0-9]|[1-9][0-9]{0,3})$ ]]; then
      echo "$port is formated properly"
    else
      echo "$port is not the correct format"
    fi
  done

  echo ""

  echo "-- Open port checker --"
fi
echo "host,port"
for host in $(cat $hostfile); do
  for port in $(cat $portfile); do
    timeout .1 bash -c "echo >/dev/tcp/$host/$port" 2>/dev/null && echo "$host,$port"
  done
done

Sources:

https://stackoverflow.com/questions/48294077/regex-to-validate-the-numbers-between-0-to-65535

https://stackoverflow.com/questions/6482377/check-existence-of-input-argument-in-a-bash-shell-script

https://stackoverflow.com/questions/13777387/check-for-ip-validity

Notes:

There is a difference when running nmap commands with sudo and without sudo:

Last updated