Created
March 11, 2015 02:53
-
-
Save lanrat/0746c7a265a5e9937821 to your computer and use it in GitHub Desktop.
netstat in bash with proc
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 | |
#get all data | |
ROUTE=$(cat /proc/net/route | grep -v "Iface") | |
TCP=$(cat /proc/net/tcp | grep "[0-9]: ") | |
UDP=$(cat /proc/net/udp | grep "[0-9]: ") | |
SOCKETS=$(ls -l $(find /proc/*/fd/ -type l 2>/dev/null) 2>/dev/null | grep socket) | |
parse_ipv4() | |
{ | |
echo "$((16#${1:6:2})).$((16#${1:4:2})).$((16#${1:2:2})).$((16#${1:0:2}))" | |
} | |
parse_port() | |
{ | |
echo "$((16#$1))" | |
} | |
lookup_socket() | |
{ | |
inode=$1 | |
matches=$(echo "$SOCKETS" | grep "socket:\[$inode\]") | |
pid=$(echo "$matches" | sed 's/.*\/proc\/\(.*\)\/fd\/.*/\1/') | |
echo $pid | |
} | |
get_program() | |
{ | |
ps=$(ps --no-headers -f $1) | |
a=($ps) | |
program=${a[8]} | |
echo $program | |
} | |
parse_line() | |
{ | |
status=${4} | |
if [[ $status == "01" ]]; | |
then | |
# only want listening | |
return | |
fi | |
port=$(parse_port ${2:9:4}) | |
ip=$(parse_ipv4 ${2:0:8}) | |
uid=${8} | |
inode=${10} | |
pid=$(lookup_socket $inode) | |
program=$(get_program $pid) | |
printf "%15s:%-6s\t%-6s\t%-6s %s\n" $ip $port $uid $pid $program | |
} | |
parse_route() | |
{ | |
iface=$1 | |
gw=$(parse_ipv4 $3) | |
dest=$(parse_ipv4 $2) | |
mask=$(parse_ipv4 $8) | |
printf "%10s\t%15s\t%15s/%-15s\n" $iface $gw $dest $mask | |
} | |
printf "%10s\t%15s\t%15s/%-15s\n" "Iface" "Gateway" "Destination" "Mask" | |
while read -r line; | |
do | |
parse_route $line | |
done <<< "$ROUTE" | |
echo "" | |
printf "%15s:%-6s\t%-6s\t%-6s %s\n" "TCP IP" "PORT" "UID" "PID" "CMD" | |
while read -r line; | |
do | |
parse_line $line | |
done <<< "$TCP" | |
echo "" | |
printf "%15s:%-6s\t%-6s\t%-6s %s\n" "UDP IP" "PORT" "UID" "PID" "CMD" | |
while read -r line; | |
do | |
parse_line $line | |
done <<< "$UDP" | |
echo "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome!