scripts/bash/pt_masscan.sh
#!/usr/bin/env bash

### BEGIN SCRIPT HEADER
SCRIPT_PATH=$(readlink -f "${BASH_SOURCE[0]}")
SCRIPT_NAME=$(basename "${SCRIPT_PATH}")
DIR_SCRIPT=$(dirname "${SCRIPT_PATH}")
COMMON="${DIR_SCRIPT}/common.sh"
source "$COMMON" || exit
### END SCRIPT HEADER

### BEGIN COMMON
function print_usage_and_exit() {
    print_info "Usage: ${SCRIPT_NAME} <PORT> <TARGET_FILE> [RATE]"
    exit
}

check_argc $# 2 || print_usage_and_exit
### END COMMON

PORT=$1
FILE=$2
RATE=1000

if [ $# -gt 2 ];
then
    print_info "Using custom rate value: ${3}"
    RATE=${3}
fi

test_file_exists "${FILE}" || exit
test_command_exists "masscan" || exit
test_command_exists "nmap" || exit
test_directory_exists "./${FOLDER_NAME_NMAP}" || exit
test_directory_exists "./${FOLDER_NAME_RECON}" || exit

TIMESTAMP=$(get_timestamp)
OUT_FILE_MASSCAN="./${FOLDER_NAME_NMAP}/masscan_tcp_${PORT}_${TIMESTAMP}.txt"
OUT_FILE_IP_PORT="./${FOLDER_NAME_NMAP}/ips_${PORT}_${TIMESTAMP}.txt"
OUT_FILE_NMAP_PREFIX="./${FOLDER_NAME_NMAP}/nmap_${PORT}_${TIMESTAMP}"

sudo masscan -p${PORT} --open --rate=${RATE} -oL "${OUT_FILE_MASSCAN}" -iL "${FILE}"
print_info "Masscan result written to: ${OUT_FILE_MASSCAN}"
if [ $? -eq 0 ]
then
    candidates=$(grep 'open' "${OUT_FILE_MASSCAN}")
    if [ $? -eq 0 ]
    then
        echo "$candidates" | cut -d' ' -f4 > $OUT_FILE_IP_PORT
        nmap -v -p${PORT} -sT -T4 -sVC -Pn --open --reason -iL "${OUT_FILE_IP_PORT}" -oA "${OUT_FILE_NMAP_PREFIX}"
        print_info "Nmap result written to: ${OUT_FILE_NMAP_PREFIX}.nmap"
    else
        print_warning "No host found for TCP port ${PORT}."
    fi
fi