Below is a handy script to capture and log access to a specific port on a server, the reason for its existence was the need to phase out an old service but we were not too sure as to what still connected to it.

By logging the unique access to the port we could then reconfigure the connecting servers to use a new service.

Sample of netstat output:

tcp 0 0   2542.42.69.1:12345     ESTABLISHED

Monitoring port access is easily achieved using netstat, a simple shell script enables me to cleanly capture the source IP, and if its not present in my capture list then I can add it, along with the Date and Time. To make it easy to handle the file, I have written the output in a CSV format.

The script sits in a tight loop to capture transient connections quickly. The port I am trying to capture is Port 25 (SMTP) and the last octet of the IP is 10, so we filter for 10:25 to narrow the hit down to the destination IP. You could also use cut to get the destination IP and filter on the “:” to capture a range of ports if needed.

I also check if the datafile being written is zero length using “stat“, if nothing is captured then no processing takes place. Since netstat can produce multiple lines when there and many inbound connections Established, I write all of them to a datafile to process one at a time.


touch ${IPFILE}
while true
	netstat -nat| grep "10:25" | grep ESTABLISHED > $DATAFILE
	SIZE=`stat -c '%s' ${DATAFILE}`
	if [ "$SIZE" -ne 0 ]
		DATE=`date '+%Y-%m-%d'`
		TIME=`date '+%H:%M:%S'`
		echo "Process data!"
		while read line
			IP=`echo $line | cut -d' ' -f5| cut -d':' -f1`
			grep ${IP} ${IPFILE}
			if [ $? == 1 ]
				echo "Add ${IP} to file ${IPFILE}"
				echo "${DATE},${TIME},${IP}" >> ${IPFILE}
		done < $DATAFILE
		echo "waiting....."