Tuesday, December 3, 2024

list open ports

 lsof -nP -iTCP -sTCP:LISTEN


ss -tunlp

netstat -tnlp


apt-get install procps
apt install net-tools
apt install iproute2 net-tools procps



#!/bin/bash # This script lists processes with open TCP ports by reading /proc/net/tcp and # matching socket inodes to file descriptors in /proc/[pid]/fd directories. # Function to convert hexadecimal port number to decimal. convert_port() { local hex_port=$1 echo $((16#$hex_port)) } echo "Processes with open TCP ports (based on /proc):" printf "%-8s %-20s %-6s\n" "PID" "Process Name" "Port" echo "-------------------------------------------" # Skip the header line from /proc/net/tcp by using tail. tail -n +2 /proc/net/tcp | while read -r line; do # Extract the local address (field 2) and the socket inode (field 10). local_address=$(echo "$line" | awk '{print $2}') inode=$(echo "$line" | awk '{print $10}') # If inode is empty, skip this line. if [[ -z "$inode" ]]; then continue fi # Extract the port (in hex) from the local_address (format: IP:PORT). port_hex=$(echo "$local_address" | cut -d':' -f2) port=$(convert_port "$port_hex") # Use find to look for file descriptors linking to this socket inode. pids=$(find /proc/[0-9]*/fd -lname "socket:\[$inode\]" 2>/dev/null | \ cut -d'/' -f3 | sort -u) # For each matching process, retrieve the process name. for pid in $pids; do if [ -f "/proc/$pid/comm" ]; then pname=$(cat /proc/$pid/comm) else pname="N/A" fi printf "%-8s %-20s %-6s\n" "$pid" "$pname" "$port" done done



List all processes:

#!/bin/bash
# This script lists all processes by scanning the /proc filesystem.

# Print header
printf "%-8s %-s\n" "PID" "Process Name"
printf "%-8s %-s\n" "--------" "----------------"

# Loop over directories in /proc that are numerical
for pid_dir in /proc/[0-9]*; do
    pid=$(basename "$pid_dir")
    
    # Check for the existence of the comm file which contains the process name
    if [ -f "$pid_dir/comm" ]; then
        proc_name=$(cat "$pid_dir/comm")
    else
        proc_name="N/A"
    fi
    
    printf "%-8s %-s\n" "$pid" "$proc_name"
done

No comments:

Post a Comment