Last Updated: February 25, 2016
·
1.101K
· vjt

Show IPv4 sockets open by your processes matching a regex

If you're asking which connections your application servers have opened, for debugging or for security reasons, this script provides a nice wrapper around ps and lsof to display all the IPv4 sockets opened by the processes running as the current user and whose command line matches the regex passed as the first parameter.

Example: here you see four unicorn workers, running on 10.0.0.1 under the app user, and each of them has a TCP socket open to a database running on port 10.0.0.2, on port 12345:

# sudo -u app ~rails/bin/list-my-open-sockets
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
ruby    26010 app    8u  IPv4 667051      0t0  TCP 10.0.0.1:47063->10.0.0.2:12345 (ESTABLISHED)
ruby    26011 app    8u  IPv4 617275      0t0  TCP 10.0.0.1:47064->10.0.0.2:12345 (ESTABLISHED)
ruby    26012 app    8u  IPv4 664804      0t0  TCP 10.0.0.1:47065->10.0.0.2:12345 (ESTABLISHED)
ruby    26013 app    8u  IPv4 619068      0t0  TCP 10.0.0.1:47066->10.0.0.2:12345 (ESTABLISHED)

Share & love :-),

-vjt

#!/bin/sh
#
# Lists all open IPv4 sockets allocated by the current
# user's processes whose command line matches the regex
# given as the first parameter.
#
# Uses "unicorn.*worker" by default, because we all
# love unicorns! :-)
#
# - vjt@openssl.it  Tue Nov 20 19:06:08 CET 2012
# - https://gist.github.com/4119806

# Get process from the first argument
PROC=$1
USER=$(whoami)
DEFP="unicorn.*worker"

case "$PROC" in
  -h|--help|--usage)
    echo "Displays the IPv4 sockets opened by the current user's"
    echo "processes matching the given regexp (default: \\"$DEFP\\")"
    echo "Usage: $0 [process regex]"
    echo
    exit 1
  ;;
esac
[ -z "$PROC" ] && PROC=$DEFP

# Wrap the first letter of the regexp within square brackets, to
# avoid `grep` itself coming out in the output.
PROC=$(echo $PROC | sed -r 's#(^.)(.*)#[\\1]\\2#')

# Get the PIDs matching the resulting regex.
PIDS=$(ps -U $USER -o pid,cmd | grep "$PROC" | cut -f1 -d' ' | tr '\\n' ',')

# Run!
lsof -nP -p $PIDS -a -i4 2>/dev/null

# Forward the exit status
exit $!