Skip to content

Instantly share code, notes, and snippets.

@aclisp
Last active November 17, 2017 02:29
Show Gist options
  • Save aclisp/697279bd75fd17e0232945cd2e8b08d0 to your computer and use it in GitHub Desktop.
Save aclisp/697279bd75fd17e0232945cd2e8b08d0 to your computer and use it in GitHub Desktop.
#!/bin/bash
if [[ $# -ne 2 ]]; then
echo "Need parameters: PROCESS_NAME showpid|showport|showhost|showconn"
exit 1
fi
PROCESS_NAME=$1
ACTION=$2
PIDS=$(pgrep -f $PROCESS_NAME | tr -s '[:space:]' ',')
PIDS=${PIDS%?}
if [[ $ACTION == "showpid" ]]; then
ps -p $PIDS -o cmd= | grep -v '^/bin/bash' | awk '{print $1}' | sort -u
exit
fi
PORTS=$(lsof -anP -iTCP -sTCP:LISTEN -p $PIDS | grep -E 'TCP .+:[0-9]+ ' -o | awk -F':' '{print $2}' | tr -s '[:space:]' '|')
PORTS=${PORTS%?}
if [[ $ACTION == "showport" ]]; then
lsof -anP -iTCP -sTCP:LISTEN -p $PIDS | grep -E 'TCP .+:[0-9]+ ' -o | awk -F':' '{print $2}' | sort -nu
exit
fi
if [[ $ACTION == "showhost" ]]; then
lsof -anP -iTCP -sTCP:ESTABLISHED -p $PIDS | grep -E "TCP .+:($PORTS)->.+:[0-9]+ " -o | awk -F'->' '{print $2}' | awk -F':' '{print $1}' | sort -u
exit
fi
if [[ $ACTION == "showconn" ]]; then
lsof -anP -iTCP -sTCP:ESTABLISHED -p $PIDS | grep -E "TCP .+:($PORTS)->.+:[0-9]+ " -o
exit
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment