I.T. Security and Linux Administration

May 28 2010   6:47PM GMT

Port Checker



Posted by: Eric Hansen
bash scripting, check, port

A while ago, I got bored and decided to venture into the realm of scripting.  Managing server after server, typing “netstat -ntlup | grep…” got annoying after a while, so I decided to write this.

The script requires the runner/user to be root.  Which is flawed, I know, but this works for me…if you want/need it modified, then I’ll do my best to help.

#!/bin/bash

# Script is used to determine if a port is used.
# Usage: portcheck <port number>
# Executes netstat -ntlup | grep <port> to do checking.
# Returned text is stored in a variable.  If variable is empty, 
# port is not in used.  Otherwise, port is being used.

# Get the username of the person running script
USER=`id -un`

# Root is required to run netstat -ntlup
if [ "$USER" != "root" ]; then
	echo "Root privileges required."
else
	NET=`netstat -ntlup | grep $1`

	if [ -z "$NET" ]; then
		echo "Port is free"
	else
		echo $NET
	fi
fi

This can check against either a port or program name (which is why root privileges is demanded).

Comment on this Post

Leave a comment: