Skip to content

Instantly share code, notes, and snippets.

@0xZDH
Last active May 18, 2021 17:12
Show Gist options
  • Select an option

  • Save 0xZDH/68f70e6c50ad7b45d90192592e89fca0 to your computer and use it in GitHub Desktop.

Select an option

Save 0xZDH/68f70e6c50ad7b45d90192592e89fca0 to your computer and use it in GitHub Desktop.
Continuously monitor the network connections on OS X.
#!/bin/bash
#
# OSX Monitor: Continuously monitor network connections on OS X
#
VERSION="0.1"
# Confirm a PID (provided by the user) exists within the list of
# running processes with open network connections
check_pid () {
local __array=( "$1" )
local __match="$2"
[[ "${__array[@]}" =~ "${__match}" ]] && return 0 || return 1
}
# Continuously monitor the network files
run() {
local __pid
local __confirm
while : ; do
# Clear the screen each refresh
clear
echo "[*] Processes with open network connections:"
echo
# Grab the list of PIDs for open network connections via
# `lsof`
PID_LIST=( $( lsof -ti | tr '\n' ' ' 2>/dev/null ) )
# Display the current processes that have open internet
# connections -> | UID, PID, Command |
ps -o uid,pid,command -p "${PID_LIST[@]}" 2>/dev/null
echo
echo
# Ask the user if they want to view a process
# Wait 10 seconds before we force a refresh of the PID
# list
read -t 10 -p "pid> " __pid
# Check if the user wants to quit
[[ "$__pid" =~ [Qq](uit)? ]] && exit 0
# If a user has entered a valid PID, present them the network
# information and provide an option to terminate the process
if check_pid "${PID_LIST[*]}" "$__pid"; then
echo
# Display network information for the given PID
lsof -i | awk -v var="$__pid" '{if ($2 == var) print $0;}' 2>/dev/null
echo
read -t 30 -p "Kill process (y/n): " __confirm
[[ "$__confirm" =~ [Yy][Ee]?[Ss]? ]] && kill -9 "$__pid" >/dev/null 2>&1
fi
unset __pid
unset __confirm
done
}
# Execute
run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment