Last active
October 9, 2024 16:41
-
-
Save rleap-m/0c3cef97b0818e6f3b212f393aa7da12 to your computer and use it in GitHub Desktop.
Checks the status of specified ports on a system output as columnar data including protocol, local address, process name, and PID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Port Checker Script | |
# This Bash script checks the status of specified network ports on a system. | |
# It utilizes the `ss` command to determine if each port is being listened to | |
# and retrieves associated process information, including the protocol (Netid), | |
# local address, process name, and PID. The output is formatted in a columnar | |
# structure for easy reading. The script requires elevated privileges to access | |
# process information. | |
# | |
# Usage: | |
# ./check_ports.sh <port1> <port2> ... <portN> | |
# Check if at least one argument (port) is provided | |
if [ "$#" -eq 0 ]; then | |
echo "Usage: $0 <port1> <port2> ... <portN>" | |
exit 1 | |
fi | |
# Use sudo to execute the ss command | |
sudo ss -tulnp &> /dev/null | |
if [ $? -ne 0 ]; then | |
echo "This script requires elevated privileges to check the ports." | |
echo "Please run it with sudo." | |
exit 1 | |
fi | |
# Print header | |
printf "%-10s %-10s %-30s %-20s %-10s\n" "PortNum" "Netid" "LocalAddress" "ProcessName" "PID" | |
printf "%-10s %-10s %-30s %-20s %-10s\n" "-------" "-----" "-------------" "------------" "----" | |
# Sort the ports numerically and iterate over each provided port | |
for port in $(printf "%s\n" "$@" | sort -n); do | |
# Use 'ss' to check if the port is being listened to and get the process name | |
output=$(sudo ss -tulnp | grep ":$port ") | |
if [ -n "$output" ]; then | |
# Process multiple lines of output for the same port | |
while IFS= read -r line; do | |
# Extract fields | |
netid=$(echo "$line" | awk '{print $1}') # Extract Netid (protocol) | |
local_address=$(echo "$line" | awk '{print $5}') # Extract Local Address | |
process_name=$(echo "$line" | grep -oP 'users:\(\("\K[^"]+') # Extract Process Name | |
pid=$(echo "$line" | grep -oP '(?<=pid=)\d+') # Extract PID | |
# Handle empty process name case | |
if [[ -z $process_name ]]; then | |
process_name="<No Process>" | |
fi | |
# Handle empty PID case | |
if [[ -z $pid ]]; then | |
pid="<N/A>" | |
fi | |
# Output in columnar format | |
printf "%-10s %-10s %-30s %-20s %-10s\n" "$port" "$netid" "$local_address" "$process_name" "$pid" | |
done <<< "$output" | |
else | |
# If the port is not being listened to, print in the same format | |
printf "%-10s %-10s %-30s %-20s %-10s\n" "$port" "<N/A>" "<Not Listening>" "<N/A>" "<N/A>" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment