Lädt...

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


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

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

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

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

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

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

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
  1. Run the script with either a process name or a PID as the argument:
   ./monitor_connections.sh <process_name_or_PID>

Example usage:

./monitor_connections.sh nginx

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

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

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
  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.

...

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


📈 46.95 Punkte
🔧 Programmierung

🔧 Bash Script Series: Automating Log Analysis with Bash Script or Shell Script


📈 38.66 Punkte
🔧 Programmierung

🔧 Bash Script Series: Automating Log Analysis with Bash Script or Shell Script


📈 38.66 Punkte
🔧 Programmierung

🔧 Bash Script Series: The Mysterious Bash Script Challenge: A Fun and Creative Exploration


📈 31.99 Punkte
🔧 Programmierung

🐧 Bash Script Include Another Bash Script


📈 31.99 Punkte
🐧 Linux Tipps

🔧 Back to bash: Inception, running bash inside bash


📈 27.98 Punkte
🔧 Programmierung

🎥 Bash Scripting - BASH Scripts For Heavy Commandline Users [Bash Snippets]


📈 27.98 Punkte
🎥 IT Security Video

🎥 Bash Scripting - BASH Scripts For Heavy Commandline Users [Bash Snippets]


📈 27.98 Punkte
🎥 IT Security Video

🔧 What is the difference between Bash shells and the Bash Script?


📈 25.32 Punkte
🔧 Programmierung

🎥 What is a Bash Script? [13 of 20] | Bash for Beginners


📈 25.32 Punkte
🎥 Video | Youtube

📰 Bash add pause prompt in a shell script ( bash pause command )


📈 25.32 Punkte
🐧 Unix Server

🐧 How can a bash script ssh command fail by just changing the script name?


📈 22.67 Punkte
🐧 Linux Tipps

🐧 VoidLinuxInstaller script, my first bash script!


📈 22.67 Punkte
🐧 Linux Tipps

📰 How to improve your bash/sh shell script with ShellCheck lint script analysis tool


📈 22.67 Punkte
🐧 Unix Server

🐧 Information about &quot;'Script with Backup data in a certain time with BASH Script&quot;


📈 22.67 Punkte
🐧 Linux Tipps

🔧 Monitor Docker Logs in Real-Time with a Simple Bash Script


📈 22.36 Punkte
🔧 Programmierung

🐧 Bashtop: Linux resource monitor written only in Bash script


📈 22.36 Punkte
🐧 Linux Tipps

🐧 Having some fun with Network Namespaces; built a network performance monitor for my home network


📈 21.44 Punkte
🐧 Linux Tipps

🐧 Write a bash script to audit network bandwidth


📈 21.02 Punkte
🐧 Linux Tipps

🐧 toggle-monitor-grayscale: a script to toggle your monitor between color and grayscale


📈 19.4 Punkte
🐧 Linux Tipps

🎥 How to Use Redirection and Pipelines in Bash [11 of 20] | Bash for Beginners


📈 18.65 Punkte
🎥 Video | Youtube

🎥 How to Modify File Permissions in Bash [12 of 20] | Bash for Beginners


📈 18.65 Punkte
🎥 Video | Youtube

🎥 What are Variables in Bash? [14 of 20] | Bash for Beginners


📈 18.65 Punkte
🎥 Video | Youtube

matomo