Friday, March 4, 2011

customized slow output on a console

One of the primary scripts I run on my desktop embedded urxvt terminals is an active connections display script. Its primary function is to utilize 'netstat' and 'lsof' to display all TCP/UDP connections to/from my system. The problem comes with running apps such as firefox or feed readers where multiple connections are established that most of the output scrolls away very fast. So I customized the script to slowly output line by line:

#!/bin/bash
echo "" > connpoll.log
function read_file()
{
        count=0
        while read line  
        do
                echo -e "$line"  
                count=$[$count+1]
                sleep .15
                if [ $count -eq 12 ]
                then
                        count=0
                        sleep 3
                fi
        done < connpoll.log
}
while [ 1 ]
do
    echo ">>>>>>>>>>>==ACTIVE CONNECTIONS VIA LSOF==<<<<<<<<<<<" > connpoll.log
        lsof -w | grep -e TCP -e UDP >> connpoll.log
    echo ">>>>>>>>>>>==ACTIVE CONNECTIONS VIA NETSTAT==<<<<<<<<<<<" >> connpoll.log
    netstat --tcp --udp -e -e -a --raw --program -v >> connpoll.log
    read_file
    sleep 8
done


The infinite while loop runs the 2 commands, directs the output to a file (connpoll.log) and executes the function 'read_file'. 'read_file' takes the file and feeds it to an internal read in the while loop which simply echos a line from the file. The 'sleep .15' provides a small time break between each line and makes the output smooth.

The script works flawlessly and with the least overhead that I could accomplish.

No comments: