How to create a Bash script to save the netstat command output to a CSV file

How to create a Bash script to save the netstat command output to a CSV file

This article will explain how to create a Bash script that runs the netstat command, filters and formats the results, and saves them to a CSV file.

The netstat command is a powerful tool that provides information about network connections, network interfaces, and other network-related system statistics. If you want to save this information in a structured format, such as a CSV file, you can easily do so using a Bash script. This article will explain how to create a Bash script that runs the netstat command, filters and formats the results, and saves them to a CSV file.

The netstat command generates output that can vary depending on the options used. For example, the netstat -tun command displays active TCP and UDP connections, along with their associated port numbers and IP addresses:


Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 192.168.1.10:22 192.168.1.100:54512 ESTABLISHED
tcp 0 0 192.168.1.10:80 192.168.1.101:60912 TIME_WAIT
udp 0 0 0.0.0.0:68 0.0.0.0:*

To save this information to a CSV file, we will need to remove the header and format the output so that each field is separated by a comma. comma.


#!/bin/bash

# Name of CSV output file
output_file="netstat_output.csv"

# Add header to CSV file
echo "Protocol,Recv-Q,Send-Q,Local Address,Foreign Address,State" > $output_file

# Run netstat command and format output to CSV
netstat -tun | tail -n +3 | awk '{print $1","$2","$3","$4","$5","$6}' >> $output_file

# Display completion message
echo "The netstat information has been saved to $output_file."

Script explanation:

  • output_file="netstat_output.csv": Defines the name of the CSV file where the data will be saved.
  • echo "Protocol,Recv-Q,Send-Q,Local Address,Foreign Address,State" > $output_file: Adds a header to the CSV file with the column names.
  • netstat -tun | tail -n +3 | awk '{print $1","$2","$3","$4","$5","$6}' >> $output_file:
    • netstat -tun: Runs the netstat command to display TCP and UDP connections.
    • tail -n +3: Removes the first two lines of netstat output, which usually include the header.
    • awk '{print $1","$2","$3","$4","$5","$6}': Uses awk to format the output, separating each field with a comma.
  • >> $output_file: Adds formatted data to the CSV file.

Enhancements and advanced options:

  • Add a timestamp to the collected data to track when the information was recorded.
  • Filter the netstat output to only show connections that are active (ESTABLISHED), listening (LISTEN), or in a specific state.
  • Schedule the script to automatically run data collection at regular intervals using cron.

Conclusion

Saving netstat information to a CSV file with a Bash script is a simple and useful process for monitoring network connections. This script can be adapted to meet specific needs and automate network data collection.