Skip to content

Instantly share code, notes, and snippets.

@xh4n3
Created September 23, 2016 08:42
Show Gist options
  • Save xh4n3/5b082693bd06a8c64f22adf5b921a286 to your computer and use it in GitHub Desktop.
Save xh4n3/5b082693bd06a8c64f22adf5b921a286 to your computer and use it in GitHub Desktop.
check ports opened in docker container of Host mode
#!/bin/sh
# Port Exporter
#
# Description:
# When docker containers are running in Host mode, thus /proc/[int]/net are shared across all containers.
# This script mimicks the "netstat -nlp".
# Firstly it finds all fds in current container into $FDS, then traverses /proc/[int]/net/tcp and /proc/[int]/net/tcp6 to collect fds. If any fd is in $FDS, the port is presumed to be opened in current container.
#
# if SKIP_PORT_CHECK is set, skip port check
if [ "$SKIP_PORT_CHECK" ]; then
exit 0
fi
# below new line is made deliberately
IFS=$"
"
# stores all port found
PORTS_ARRAY=""
# Finds all PID
PIDS=$(ls /proc | grep -G '^[0-9]*$')
for PID in $PIDS
do
# Skips non-exist PID by script itself
FDS=$(ls -al /proc/$PID/fd 2> /dev/null)
if [ "$?" -ne "0" ]; then
continue
fi
# Parse all FDs
FDS=$(echo "$FDS" | grep socket | awk -F[ '{ print $2 }' | awk -F] '{ print $1 }')
contains () {
for INODE in $FDS
do
if [ $INODE -eq $1 ]; then
# Parse hex port to decimal, append to PORTS_ARRAY
PORTS_ARRAY="$PORTS_ARRAY\n$((0x$2))"
fi
done
}
TCP_LINES=$(cat /proc/$PID/net/tcp /proc/$PID/net/tcp6 | grep \ 0A\ )
for LINE in $TCP_LINES
do
INODE=$(echo $LINE | awk '{ print $10 }')
PORT=$(echo $LINE | awk '{ print $2 }' | awk -F: '{ print $2 }')
contains $INODE $PORT
done
done
echo -n $PORTS_ARRAY
FOUND=$(echo $PORTS_ARRAY | grep -e "^$PORT_TO_CHECK$")
# if no port provided and at least one port being found in PORTS_ARRAY
if [ ! "$PORT_TO_CHECK" ] && [ !"$PORTS_ARRAY" ]; then
exit 0
# $PORT_TO_CHECK found in $PORTS_ARRAY
elif [ "$PORT_TO_CHECK" ] && [ "$FOUND" != "" ]; then
exit 0
else
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment