Skip to content

Instantly share code, notes, and snippets.

@signus
Last active June 23, 2021 18:46
Show Gist options
  • Save signus/917eee291b90056af1ef to your computer and use it in GitHub Desktop.
Save signus/917eee291b90056af1ef to your computer and use it in GitHub Desktop.
#!/bin/bash
# Signus
# Compares discovered ports from nmap to a list provided as acceptable ports. Any found ports that aren't accepted throw an 'exit 1' to cause Jenkins to mark a build failed.
RD='\033[0;31m'
GRN='\033[0;32m'
NC='\033[0m'
ports=()
allow=()
function usage {
echo "usage: $0 [-h host/IP] [-a allow_port_list]"
exit 1
}
while getopts ":h:a:" option; do
case $option in
h)
host="$OPTARG"
;;
a)
allowList="$OPTARG"
;;
\?)
echo -e "${RD}Invalid option - $OPTARG${NC}"
usage
;;
*)
usage
;;
esac
done
NMAP_OUTPUT=`nmap -v $host`
REGEX="Discovered open port ([0-9]{2,5})"
if [[ "$#" -ne 4 ]]; then
echo -e "${RD}Invalid number of arguments.${NC}"
usage
fi
# Put comma separated values into array
for i in $(echo $allowList | sed "s/,/ /g"); do
allow+=("$i")
done
# Read nmap output and check for open ports
while read line; do
echo $line
if [[ $line =~ $REGEX ]]; then
ports+=("${BASH_REMATCH[1]}")
fi
done <<< "$NMAP_OUTPUT"
# Check the difference of open ports and acceptable ports
for i in "${allow[@]}"; do
ports=(${ports[@]//*$i*})
done
for p in "${ports[@]}"; do
echo -e "${RD}[-] Port $p should not be open.${NC}"
done
[[ -z "$ports" ]] && exit 0 || exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment