DEV Community

Dmitry Romanoff
Dmitry Romanoff

Posted on

How to Monitor Network Connections of a Process with a Bash Script

As a developer or system administrator, monitoring the network connections used by a specific process can be incredibly useful for troubleshooting and performance optimization. Whether you want to check which ports a process is using or how it interacts with the network, being able to do this efficiently can save you time and help pinpoint potential issues.

In this article, we'll walk through a simple Bash script that continuously monitors network connections of a given process and outputs relevant information in real-time. We’ll explore how to use the script, explain the logic behind it, and share tips on how you can customize it further.

Prerequisites

Before we dive into the script, let’s take a look at some of the tools we’ll be using:

  1. lsof: This is a command-line utility used to list open files and the processes that opened them. By using the -i option, we can monitor network connections associated with a specific process.
  2. pgrep: This command helps find the process IDs (PID) of running processes based on their name or other attributes.

The Script

Below is the Bash script that continuously monitors network connections for a given process:

#!/bin/bash

# Check if process name or PID is provided as argument
if [ -z "$1" ]; then
  echo "Usage: $0 <process_name_or_PID>"
  exit 1
fi

PROCESS=$1

# Loop forever to continuously monitor the connections
while true; do
  echo "Checking network connections for process: $PROCESS"

  # Get the PID of the given process name (if process name is given)
  if ! [[ "$PROCESS" =~ ^[0-9]+$ ]]; then
    PID=$(pgrep -f "$PROCESS")
    if [ -z "$PID" ]; then
      echo "No process found with name: $PROCESS"
      exit 1
    fi
  else
    PID="$PROCESS"
  fi

  echo "PID: $PID"

  # Check the network connections used by the process
  # Use lsof to list the connections by PID
  lsof -i -a -p $PID

  # Sleep for a specified time before checking again (e.g., 5 seconds)
  sleep 5
done
Enter fullscreen mode Exit fullscreen mode

How the Script Works

Let's break down what this script does and how each part works:

  1. Argument Validation:
   if [ -z "$1" ]; then
     echo "Usage: $0 <process_name_or_PID>"
     exit 1
   fi
Enter fullscreen mode Exit fullscreen mode

This first section checks if an argument has been passed to the script. If no argument is provided, the script outputs a usage message and exits. The argument can either be the name of a process or a process ID (PID).

  1. Process Identification:
   if ! [[ "$PROCESS" =~ ^[0-9]+$ ]]; then
     PID=$(pgrep -f "$PROCESS")
     if [ -z "$PID" ]; then
       echo "No process found with name: $PROCESS"
       exit 1
     fi
   else
     PID="$PROCESS"
   fi
Enter fullscreen mode Exit fullscreen mode

After verifying the argument, the script checks whether it’s a number (PID) or a string (process name). If it's a process name, the script uses pgrep to find the PID associated with that process. If the process is not found, it displays an error message and exits.

  1. Monitoring Network Connections:
   lsof -i -a -p $PID
Enter fullscreen mode Exit fullscreen mode

The lsof command is used to list the open network connections associated with the given process. By specifying the -i flag, it filters the results to show only network connections. The -p flag ensures that the connections are tied to the process with the provided PID. If the process is running and making network connections, they will be displayed.

  1. Continuous Monitoring:
   sleep 5
Enter fullscreen mode Exit fullscreen mode

The script then pauses for 5 seconds before checking the network connections again. This allows you to keep monitoring the process in real-time. You can adjust the sleep duration as needed to control how often the check is performed.

Running the Script

To run the script, follow these steps:

  1. Save the script to a file, for example monitor_connections.sh.
  2. Make the script executable by running:
   chmod +x monitor_connections.sh
Enter fullscreen mode Exit fullscreen mode
  1. Run the script with either a process name or a PID as the argument:
   ./monitor_connections.sh <process_name_or_PID>
Enter fullscreen mode Exit fullscreen mode

Example usage:

./monitor_connections.sh nginx
Enter fullscreen mode Exit fullscreen mode

This will monitor the network connections of all nginx processes. If you have a specific process ID (PID), you can directly pass it:

./monitor_connections.sh 12345
Enter fullscreen mode Exit fullscreen mode

Practical Use Cases

This script is helpful in various scenarios:

  • Troubleshooting Network Issues: You can identify which network connections a process is using, helping you identify whether it’s connecting to the wrong host, port, or using the wrong protocol.
  • Security Monitoring: If you're monitoring suspicious processes, you can quickly determine which network services they are communicating with.
  • Performance Analysis: Monitoring network connections of a process can reveal whether the process is sending or receiving too much data, which can be crucial for optimizing resource usage.

Customization Ideas

While the script is simple and functional, here are a few ways you can customize it:

  1. Filter Connections: You can modify the lsof command to filter connections by IP address, port, or protocol.
   lsof -i @127.0.0.1
Enter fullscreen mode Exit fullscreen mode

This will show only the connections to and from the local machine.

  1. Log to a File: Instead of printing the connections to the terminal, you can redirect the output to a log file for later analysis:
   lsof -i -a -p $PID >> network_connections.log
Enter fullscreen mode Exit fullscreen mode
  1. Alerting: Integrate this script with a monitoring tool like mail or sendmail to notify you when certain connections are detected.

Conclusion

This script offers a simple yet powerful way to monitor the network connections of a process in real-time. By using basic Linux tools like lsof and pgrep, we can track important information about network interactions of any running process. Whether you're troubleshooting, analyzing performance, or monitoring security, this script can be an invaluable part of your toolkit.

Top comments (0)