Building a Simple Port Listener in Shell Script

As a software architect, it is of utmost importance to have a solid understanding of a few networking tools and techniques. One such technique is creating a simple port listener using a shell script. This can be incredibly useful for tasks like testing network connectivity, monitoring traffic, or debugging network issues. In this blog post, we’ll guide you through the process of building a basic port listener using a shell script.

Before diving into the details, ensure you have a basic understanding of shell scripting and terminal commands. We’ll be using Linux and bash for our example.

Step 1: Creating the Shell Script
Let’s start by creating a new file for our shell script. Open the terminal and open your favorite text editor and create a file named “port_listener.sh”.

vi port_listener.sh

Step 2: Write the script

Copy the following in your script file

#!/bin/bash
read MESSAGE
echo "PID: $$"
echo "$MESSAGE"

Step 3: Making the Script Executable
Before we can run the script, we need to make it executable. Open your terminal and navigate to the directory where port_listener.sh is located. Then, run the following command:

chmod +x port_listener.sh

Step 4: Invoking script for each TCP connection

In order to invoke the script to listen to each and every message on a particular port. Run the following command

socat -u tcp-l:8080,fork system:./port_listener.sh

If socat is not installed, install socat with apt (apt install socat) or yum(yum install socat).

Step 5: Testing the script

Run following to test the script from a new terminal

echo "Hi there, this is a sample message on the port" | nc -v -w 0 localhost 8080

You should see that the connection is established, and the message appearing on the terminal running the script.

This basic example demonstrates the power of shell scripting in networking and system administration tasks. You can further enhance the script by adding error handling, logging, or implementing more advanced features.

Leave a comment

Create a website or blog at WordPress.com

Up ↑