Python Script to Monitor Network Connection and saving into Log File

Monitoring network connections is crucial for ensuring the stability and security of computer systems. Whether you're a network administrator or an individual user, having a way to track network connectivity and log relevant information can be invaluable. In this article, we'll explore how to create a Python script that monitors network connections and saves the data into a log file.

By leveraging Python's built-in libraries like socket and psutil, we can develop a script that periodically checks network connectivity, captures details such as IP addresses, timestamps, and connection statuses, and stores them in a log file for future reference.

Required Libraries

For this network monitoring script, we'll need the following libraries ?

  • socket Built-in library for network operations

  • datetime For timestamps

  • time For intervals between checks

  • psutil For system and network information (install with: pip install psutil)

Basic Network Connection Monitor

Let's start with a simple script that checks internet connectivity and logs the results ?

import socket
import datetime
import time

def check_internet_connection():
    """Check if internet connection is available"""
    try:
        # Try to connect to Google's DNS server
        socket.create_connection(("8.8.8.8", 53), timeout=3)
        return True
    except OSError:
        return False

def log_connection_status(log_file):
    """Log current connection status with timestamp"""
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    is_connected = check_internet_connection()
    status = "CONNECTED" if is_connected else "DISCONNECTED"
    
    log_entry = f"[{timestamp}] Internet Status: {status}\n"
    
    # Write to file
    with open(log_file, "a") as f:
        f.write(log_entry)
    
    print(log_entry.strip())  # Also print to console

# Create log file with timestamp
log_filename = f"network_log_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"

print(f"Starting network monitoring. Log file: {log_filename}")
print("Press Ctrl+C to stop monitoring...")

try:
    while True:
        log_connection_status(log_filename)
        time.sleep(5)  # Check every 5 seconds
        
except KeyboardInterrupt:
    print("\nMonitoring stopped by user.")
Starting network monitoring. Log file: network_log_20241201_143022.txt
Press Ctrl+C to stop monitoring...
[2024-12-01 14:30:22] Internet Status: CONNECTED
[2024-12-01 14:30:27] Internet Status: CONNECTED
[2024-12-01 14:30:32] Internet Status: CONNECTED

Advanced Network Monitoring with psutil

For more detailed network information, we can use the psutil library to monitor active connections ?

import psutil
import socket
import datetime
import time

def get_network_connections():
    """Get detailed network connection information"""
    connections = []
    
    try:
        # Get network connections
        for conn in psutil.net_connections(kind='inet'):
            if conn.status == 'ESTABLISHED':
                local_addr = f"{conn.laddr.ip}:{conn.laddr.port}" if conn.laddr else "N/A"
                remote_addr = f"{conn.raddr.ip}:{conn.raddr.port}" if conn.raddr else "N/A"
                
                connections.append({
                    'local': local_addr,
                    'remote': remote_addr,
                    'status': conn.status,
                    'pid': conn.pid
                })
    except (psutil.AccessDenied, psutil.NoSuchProcess):
        pass
    
    return connections

def log_detailed_connections(log_file):
    """Log detailed network connections"""
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    connections = get_network_connections()
    
    with open(log_file, "a") as f:
        f.write(f"\n=== Network Snapshot at {timestamp} ===\n")
        f.write(f"Total established connections: {len(connections)}\n")
        
        for i, conn in enumerate(connections, 1):
            f.write(f"{i}. Local: {conn['local']} -> Remote: {conn['remote']} "
                   f"(Status: {conn['status']}, PID: {conn['pid']})\n")
        
        f.write("-" * 50 + "\n")
    
    print(f"[{timestamp}] Logged {len(connections)} active connections")

# Usage example (requires psutil installation)
if __name__ == "__main__":
    log_file = f"detailed_network_log_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
    
    try:
        for _ in range(3):  # Run 3 times for demonstration
            log_detailed_connections(log_file)
            time.sleep(10)
    except Exception as e:
        print(f"Error: {e}")

Enhanced Network Monitor with Multiple Checks

Here's a comprehensive script that combines multiple monitoring approaches ?

import socket
import datetime
import time
import subprocess
import platform

class NetworkMonitor:
    def __init__(self, log_file):
        self.log_file = log_file
        self.start_time = datetime.datetime.now()
        
    def ping_host(self, host="8.8.8.8"):
        """Ping a host to check connectivity"""
        try:
            # Adjust ping command based on OS
            param = "-n" if platform.system().lower() == "windows" else "-c"
            result = subprocess.run(
                ["ping", param, "1", host], 
                capture_output=True, 
                text=True, 
                timeout=5
            )
            return result.returncode == 0
        except:
            return False
    
    def check_dns_resolution(self, domain="google.com"):
        """Check if DNS resolution works"""
        try:
            socket.gethostbyname(domain)
            return True
        except socket.gaierror:
            return False
    
    def get_local_ip(self):
        """Get local IP address"""
        try:
            # Connect to a remote address to get local IP
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            local_ip = s.getsockname()[0]
            s.close()
            return local_ip
        except:
            return "Unable to determine"
    
    def log_status(self):
        """Log comprehensive network status"""
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # Perform various checks
        ping_success = self.ping_host()
        dns_success = self.check_dns_resolution()
        local_ip = self.get_local_ip()
        
        # Create status summary
        status_summary = "HEALTHY" if (ping_success and dns_success) else "ISSUES"
        
        log_entry = f"""
[{timestamp}] Network Status Check
Local IP: {local_ip}
Ping Test (8.8.8.8): {'PASS' if ping_success else 'FAIL'}
DNS Resolution: {'PASS' if dns_success else 'FAIL'}
Overall Status: {status_summary}
{'='*50}
"""
        
        # Write to log file
        with open(self.log_file, "a") as f:
            f.write(log_entry)
        
        # Print to console
        print(f"[{timestamp}] Status: {status_summary} | IP: {local_ip}")
        
        return status_summary
    
    def start_monitoring(self, interval=30):
        """Start continuous monitoring"""
        print(f"Network monitoring started. Log file: {self.log_file}")
        print("Press Ctrl+C to stop...")
        
        try:
            while True:
                self.log_status()
                time.sleep(interval)
        except KeyboardInterrupt:
            runtime = datetime.datetime.now() - self.start_time
            print(f"\nMonitoring stopped. Runtime: {runtime}")

# Example usage
if __name__ == "__main__":
    log_file = f"network_monitor_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
    monitor = NetworkMonitor(log_file)
    
    # Run a single check
    status = monitor.log_status()
    print(f"Current network status: {status}")
Network monitoring started. Log file: network_monitor_20241201_143500.log
Press Ctrl+C to stop...
[2024-12-01 14:35:00] Status: HEALTHY | IP: 192.168.1.100
[2024-12-01 14:35:30] Status: HEALTHY | IP: 192.168.1.100
Current network status: HEALTHY

Key Features

Feature Basic Monitor Advanced Monitor
Internet Connectivity ? ?
DNS Resolution ? ?
Local IP Detection ? ?
Ping Testing ? ?
Structured Logging Basic Detailed

Running the Script

To use the network monitoring script ?

  1. Save the script as network_monitor.py
  2. Run it with: python network_monitor.py
  3. Check the generated log file for detailed network history
  4. Stop monitoring with Ctrl+C

Conclusion

This Python network monitoring script provides a robust solution for tracking network connectivity and logging connection details. Use the basic version for simple connectivity checks or the advanced version for comprehensive network analysis with ping tests and DNS resolution monitoring.

Updated on: 2026-03-27T12:09:48+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements