-
-
Save petermueller/1b837eddc443857b2051f739818cfad7 to your computer and use it in GitHub Desktop.
AWK to get details from /proc/net/tcp and /proc/net/udp when netstat and lsof are not available
This file contains hidden or 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/env bash | |
# Install | |
# - Get the "raw" link for the most current SHA of the file | |
# - Use that to download the file and chmod +x it to make it executable | |
# e.g. | |
# curl -o awk_netstat.sh https://gist.githubusercontent.com/.../awk_netstat.sh | |
# chmod +x awk_netstat.sh | |
# Usage | |
# ./awk_netstat $(cat /var/run/nginx.pid) | wc -l | |
# Based on gists | |
# - https://gist.github.com/staaldraad/4c4c80800ce15b6bef1c1186eaa8da9f | |
# - added TCP states | |
# - https://gist.github.com/qistoph/1b0708c888f078c3720de6c6f9562997 | |
# Check if at least one argument is provided | |
if [ $# -eq 0 ]; then | |
echo "Usage: $0 <pid> [additional arguments...]" | |
exit 1 | |
fi | |
# Get the PID from the first argument | |
PID="$1" | |
shift # Remove the first argument (PID) from the list | |
# Construct the command with any additional arguments | |
CMD="awk 'BEGIN{states[\"01\"]=\"TCP_ESTABLISHED\" | |
states[\"02\"]=\"TCP_SYN_SENT\" | |
states[\"03\"]=\"TCP_SYN_RECV\" | |
states[\"04\"]=\"TCP_FIN_WAIT1\" | |
states[\"05\"]=\"TCP_FIN_WAIT2\" | |
states[\"06\"]=\"TCP_TIME_WAIT\" | |
states[\"07\"]=\"TCP_CLOSE\" | |
states[\"08\"]=\"TCP_CLOSE_WAIT\" | |
states[\"09\"]=\"TCP_LAST_ACK\" | |
states[\"0A\"]=\"TCP_LISTEN\" | |
states[\"0B\"]=\"TCP_CLOSING\" | |
states[\"0C\"]=\"TCP_NEW_SYN_RECV\" | |
} | |
function hextodec(str,ret,n,i,k,c){ | |
ret = 0 | |
n = length(str) | |
for (i = 1; i <= n; i++) { | |
c = tolower(substr(str, i, 1)) | |
k = index(\"123456789abcdef\", c) | |
ret = ret * 16 + k | |
} | |
return ret | |
} | |
function getIP(str,ret){ | |
ret=hextodec(substr(str,index(str,\":\")-2,2)); | |
for (i=5; i>0; i-=2) { | |
ret = ret\".\"hextodec(substr(str,i,2)) | |
} | |
ret = ret\":\"hextodec(substr(str,index(str,\":\")+1,4)) | |
return ret | |
} | |
NR > 1 {{if(NR==2)print \"Local - Remote\";local=getIP(\$2);remote=getIP(\$3)}{print local\" - \"remote\" \"states[\$4]}}' /proc/$PID/net/tcp" | |
# Append any additional arguments | |
for arg in "$@"; do | |
CMD="$CMD | $arg" | |
done | |
# Execute the command | |
eval "$CMD" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment