Monitor and Log all active TCP connections

Script Name: Capture-TCPConnections.ps1

Purpose

This PowerShell script monitors and logs all active TCP connections on ports 80 (HTTP) and 443 (HTTPS) on a Windows system. It periodically saves the connection details into a CSV file for network analysis or auditing.


Key Features

  1. Monitors: Established TCP connections (Get-NetTCPConnection -State Established).

  2. Ports Tracked:

    • 80 → HTTP

    • 443 → HTTPS

  3. Logging Interval: Every 5 seconds ($IntervalSeconds = 5).

  4. Output Format: CSV file with timestamped filename.

  5. Output Location: C:\Logs\ (automatically created if it doesn’t exist).

  6. Stops Manually: Press Ctrl + C to stop the script.


Script


Step-by-Step Explanation

1. Set Output Folder

  • Checks if the folder C:\Logs exists.

  • If not, creates it to store log files.


2. Create a Timestamped Log File

  • Generates a filename with the current date and time (e.g., tcp_connections_20251009_131317.csv).


3. Write CSV Header

  • Defines column headers for the CSV file.


4. Set Logging Interval

  • Logs data every 5 seconds (can be changed).


5. Continuous Monitoring Loop

Explanation:

  • Infinite loop (while ($true)) — runs until stopped manually.

  • Gets all active TCP connections on ports 80 and 443.

  • For each connection:

    • Extracts details (local/remote address & port, state, process ID).

    • Logs the data with a timestamp.

  • Waits 5 seconds, then repeats.


6. Error Handling

  • Catches and displays any errors (e.g., permission issues, script interruption).


Sample CSV Output


Use Cases

  • Monitoring web traffic activity on a local server.

  • Tracking active HTTP/HTTPS connections for forensic or troubleshooting purposes.

  • Identifying which processes (by PID) are using network ports 80/443.

  • Useful in incident response, network auditing, or security monitoring.


Note

  • Must be run with administrator privileges to access all process and connection data.

  • You can modify $IntervalSeconds or add other ports (e.g., 22, 25, 8080) for broader monitoring.

Last updated

Was this helpful?