Thursday, September 8, 2011

Netstat shellscript

This is a shellscript i coded a couple of month ago, after i found my router didn't have this utility, and wanted to check its active connections.

It only displays TCP connections, printing the source and destination IP address and port of each of them. The script requires the sh shell interpreter, making it possible to use it in systems which don't have other interpreters like bash, which provides several features which would make the script simpler.

This is the script:


#!/bin/sh parse_num() {     x=$(echo $1 | sed -n 's/0*//p')     if [ $(echo $x | wc -c) -eq 1 ]     then         x=0     fi     echo $x } hex_to_ip() {     index=7     output=''     while [ $index -gt 0 ]     do         end=$(expr $index + 1)         value=$(printf "%d" "0x$(parse_num $(echo $1 | cut -b $index-$end))")         output="$output.$value"         index=$(expr $index - 2)     done     echo $(echo $output | cut -b 2-) } printf "         Src IP  Src port          Dst IP  Dst port\n" cat /proc/net/tcp | while read line; do     srcip=$(hex_to_ip $(echo $line | sed -n 's/^[0-9]*: //p' | sed 's/:.*//p'))     srcport=$(printf "%d" 0x$(parse_num $(echo $line | sed  -n 's/^ *[0-9]*: [0-9,A-F]*://p' | cut "-d " -f 1)))     dstip=$(hex_to_ip $(echo $line | sed -n 's/^[0-9]*: [0-9,A-F]*:[0-9,A-F]* //p' | sed -n 's/:.*//p'))     dstport=$(printf "%d" 0x$(parse_num $(echo $line | sed -n 's/^ *[0-9]*: [0-9,A-F]*:[0-9,A-F]* [0-9,A-F]*://p' | cut "-d " -f1)))         printf "%15s %9s %15s %9s\n" $srcip $srcport $dstip $dstport done


An output example:


No comments:

Post a Comment