Aller au contenu

Feuille de chaleur Netstat

Netstat - Utilitaire de connexion réseau

Netstat est un utilitaire réseau en ligne de commande qui affiche les connexions réseau, les tables de routage, les statistiques d'interface, les connexions masquerade et les abonnements multicast. Essentiel pour le dépannage du réseau, l'analyse de sécurité et l'administration du système.

Copier toutes les commandes Générer PDF

Sommaire

  • [Installation] (LINK_0)
  • [Utilisation de base] (LINK_0)
  • [Surveillance de la connexion] (LINK_0)
  • [Tableaux de départ] (LINK_0)
  • [Statistiques d'interface] (LINK_0)
  • [Renseignements sur le processus] (LINK_0)
  • [Filtrage avancé] (LINK_0)
  • [Analyse de la sécurité] (LINK_0)
  • [Scripts d'automatisation] (LINK_0)
  • [Surveillance du rendement] (LINK_0)
  • [Dépannage] (LINK_0)
  • [Meilleures pratiques] (LINK_0)

Installation

Linux (construire)

# Netstat is typically pre-installed on most Linux distributions
# If missing, install via package manager

# Ubuntu/Debian
sudo apt update
sudo apt install net-tools

# CentOS/RHEL/Fedora
sudo yum install net-tools
# or
sudo dnf install net-tools

# Arch Linux
sudo pacman -S net-tools

# Alpine Linux
sudo apk add net-tools

Fenêtres (encastrées)

# Netstat is built into Windows
# Available in Command Prompt and PowerShell
netstat /?

# PowerShell equivalent
Get-NetTCPConnection
Get-NetUDPEndpoint
```_

### MACOS (Construire)
```bash
# Netstat is pre-installed on macOS
netstat -h

# Alternative: lsof for more detailed process information
brew install lsof
```_

### Autres outils
```bash
# Modern alternatives to netstat
# ss (socket statistics) - faster and more feature-rich
sudo apt install iproute2  # Ubuntu/Debian
sudo yum install iproute2  # CentOS/RHEL

# lsof - list open files and network connections
sudo apt install lsof     # Ubuntu/Debian
sudo yum install lsof      # CentOS/RHEL

Utilisation de base

Afficher toutes les connexions

# Show all active connections
netstat -a

# Show all TCP connections
netstat -at

# Show all UDP connections
netstat -au

# Show all listening ports
netstat -l

# Show all listening TCP ports
netstat -lt

# Show all listening UDP ports
netstat -lu

Options communes

# Show numerical addresses instead of resolving hosts
netstat -n

# Show process ID and name
netstat -p

# Continuous monitoring (refresh every 2 seconds)
netstat -c

# Show extended information
netstat -e

# Show multicast group memberships
netstat -g

# Show routing table
netstat -r

# Show interface statistics
netstat -i

Options combinées

# Most commonly used combination
netstat -tulpn

# Breakdown:
# -t: TCP connections
# -u: UDP connections
# -l: Listening ports only
# -p: Show process ID and name
# -n: Show numerical addresses

# Show all connections with process information
netstat -anp

# Show listening ports with process information
netstat -lnp

# Show TCP connections with process information
netstat -tnp

Surveillance des connexions

TCP Connexions

# Show all TCP connections
netstat -t

# Show TCP connections with numerical addresses
netstat -tn

# Show TCP listening ports
netstat -tl

# Show TCP connections with process information
netstat -tp

# Show TCP connections in specific states
netstat -t | grep ESTABLISHED
netstat -t | grep LISTEN
netstat -t | grep TIME_WAIT
netstat -t | grep CLOSE_WAIT

UDP Connexions

# Show all UDP connections
netstat -u

# Show UDP connections with numerical addresses
netstat -un

# Show UDP listening ports
netstat -ul

# Show UDP connections with process information
netstat -up

États de connexion

# Monitor connection states
netstat -t | awk '{print $6}' | sort | uniq -c

# Count connections by state
netstat -an | awk '/^tcp/ {print $6}' | sort | uniq -c

# Monitor specific connection state
watch -n 1 'netstat -t | grep ESTABLISHED | wc -l'

# Show connections to specific port
netstat -an | grep :80
netstat -an | grep :443
netstat -an | grep :22

Surveillance en temps réel

# Continuous monitoring
netstat -c

# Monitor with custom interval (every 5 seconds)
watch -n 5 netstat -tulpn

# Monitor specific port continuously
watch -n 1 'netstat -an | grep :80'

# Monitor connection count
watch -n 1 'netstat -an | wc -l'

Tableaux d'acheminement

Afficher les informations de routage

# Show routing table
netstat -r

# Show routing table with numerical addresses
netstat -rn

# Show IPv4 routing table
netstat -r -4

# Show IPv6 routing table
netstat -r -6

# Show kernel routing table (Linux)
netstat -rn | grep '^0.0.0.0'

# Show default gateway
netstat -rn | grep '^default'

Analyse de la route

# Show routing table with interface information
netstat -rn | column -t

# Find routes to specific network
netstat -rn | grep "192.168.1"

# Show routing cache (if available)
netstat -C

# Display routing statistics
netstat -s | grep -i route

Statistiques sur les interfaces

Information sur l'interface réseau

# Show interface statistics
netstat -i

# Show interface statistics with extended information
netstat -ie

# Show interface statistics continuously
netstat -ic

# Show specific interface
netstat -i eth0
netstat -i wlan0

Surveillance de l'interface

# Monitor interface packet counts
watch -n 1 'netstat -i'

# Show interface errors and drops
netstat -i | awk 'NR>2 {print $1, $4, $8}'

# Monitor specific interface traffic
watch -n 1 'netstat -i | grep eth0'

# Calculate interface utilization
netstat -i | awk 'NR>2 {print $1, "RX:", $3, "TX:", $7}'

Information sur le processus

Cartographie des processus à ports

# Show processes using network connections
netstat -p

# Show processes listening on ports
netstat -lp

# Show processes using TCP connections
netstat -tp

# Show processes using UDP connections
netstat -up

# Find process using specific port
netstat -lnp | grep :80
netstat -lnp | grep :443
netstat -lnp | grep :22

Analyse des processus

# Show all processes with network connections
netstat -anp | grep -v "0.0.0.0:*"

# Find processes by name
netstat -anp | grep nginx
netstat -anp | grep apache
netstat -anp | grep mysql

# Show connections for specific PID
netstat -anp | grep 1234

# Count connections per process
netstat -anp | awk '{print $7}' | sort | uniq -c | sort -nr

Filtre avancé

Filtrage par port

# Show connections on specific port
netstat -an | grep :80
netstat -an | grep :443
netstat -an | grep :22
netstat -an | grep :3306

# Show listening services on common ports
netstat -ln | grep :80
netstat -ln | grep :443
netstat -ln | grep :22

# Show connections from specific IP
netstat -an | grep 192.168.1.100

# Show connections to specific IP
netstat -an | grep "192.168.1.100:"

Filtrage des protocoles

# Show only TCP connections
netstat -t

# Show only UDP connections
netstat -u

# Show only Unix domain sockets
netstat -x

# Show only raw sockets
netstat -w

# Show IPv4 connections only
netstat -4

# Show IPv6 connections only
netstat -6

Filtrage par l'État

# Show established connections
netstat -t | grep ESTABLISHED

# Show listening ports
netstat -t | grep LISTEN

# Show connections in TIME_WAIT state
netstat -t | grep TIME_WAIT

# Show connections in CLOSE_WAIT state
netstat -t | grep CLOSE_WAIT

# Count connections by state
netstat -t | awk '{print $6}' | sort | uniq -c

Analyse de la sécurité

Surveillance de la sécurité

# Monitor for suspicious connections
netstat -an | grep ESTABLISHED | grep -v "127.0.0.1\|::1"

# Check for unexpected listening services
netstat -ln | grep -v "127.0.0.1\|::1"

# Monitor for connections to unusual ports
netstat -an | grep -E ":(1234|4444|5555|6666|7777|8888|9999)"

# Check for connections from external IPs
netstat -an | grep ESTABLISHED | grep -v "192.168\|10\.\|172\."

Détection de balayage de port

# Monitor for port scanning attempts
netstat -an | grep SYN_RECV | wc -l

# Check for half-open connections
netstat -an | grep SYN_RECV

# Monitor connection attempts
watch -n 1 'netstat -an | grep SYN_RECV | wc -l'

# Detect potential DDoS
netstat -an | grep :80 | grep SYN_RECV | wc -l
# Capture current network state
netstat -anp > network_state_$(date +%Y%m%d_%H%M%S).txt

# Monitor network changes
netstat -anp > /tmp/netstat_before.txt
# ... perform action ...
netstat -anp > /tmp/netstat_after.txt
diff /tmp/netstat_before.txt /tmp/netstat_after.txt

# Track connection history
while true; do
    echo "$(date): $(netstat -an | wc -l) connections" >> connection_log.txt
    sleep 60
done

Scripts d'automatisation

Scénario de surveillance du réseau

#!/bin/bash
# network_monitor.sh - Comprehensive network monitoring

LOG_FILE="/var/log/network_monitor.log"
ALERT_THRESHOLD=1000

log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

check_connections() {
    local conn_count=$(netstat -an | wc -l)
    log_message "Total connections: $conn_count"

    if [ "$conn_count" -gt "$ALERT_THRESHOLD" ]; then
        log_message "ALERT: High connection count detected!"
        # Send alert (email, Slack, etc.)
    fi
}

check_listening_ports() {
    log_message "Listening ports:"
    netstat -ln | grep LISTEN | tee -a "$LOG_FILE"
}

check_established_connections() {
    local est_count=$(netstat -an | grep ESTABLISHED | wc -l)
    log_message "Established connections: $est_count"
}

check_suspicious_activity() {
    # Check for connections to unusual ports
    local suspicious=$(netstat -an | grep -E ":(1234|4444|5555|6666|7777|8888|9999)" | wc -l)
    if [ "$suspicious" -gt 0 ]; then
        log_message "WARNING: Suspicious connections detected!"
        netstat -an | grep -E ":(1234|4444|5555|6666|7777|8888|9999)" | tee -a "$LOG_FILE"
    fi
}

main() {
    log_message "Starting network monitoring"
    check_connections
    check_listening_ports
    check_established_connections
    check_suspicious_activity
    log_message "Network monitoring completed"
}

# Run monitoring
main

Détection du scanner de port

#!/bin/bash
# port_scan_detector.sh - Detect potential port scanning

SCAN_LOG="/var/log/port_scan.log"
THRESHOLD=10

detect_syn_flood() {
    local syn_count=$(netstat -an | grep SYN_RECV | wc -l)

    if [ "$syn_count" -gt "$THRESHOLD" ]; then
        echo "$(date): ALERT - Potential SYN flood detected! Count: $syn_count" >> "$SCAN_LOG"

        # Log source IPs
        echo "Source IPs:" >> "$SCAN_LOG"
        netstat -an | grep SYN_RECV | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr >> "$SCAN_LOG"

        # Optional: Block suspicious IPs
        # netstat -an | grep SYN_RECV | awk '{print $5}' | cut -d: -f1 | sort | uniq | while read ip; do
        #     iptables -A INPUT -s "$ip" -j DROP
        # done
    fi
}

monitor_connection_attempts() {
    # Monitor for rapid connection attempts
    netstat -an | grep SYN_RECV | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | while read count ip; do
        if [ "$count" -gt 5 ]; then
            echo "$(date): Suspicious activity from $ip - $count connection attempts" >> "$SCAN_LOG"
        fi
    done
}

# Run detection
detect_syn_flood
monitor_connection_attempts

Analyseur de connexion

#!/usr/bin/env python3
# connection_analyzer.py - Advanced connection analysis

import subprocess
import re
import json
from collections import defaultdict, Counter
from datetime import datetime

class ConnectionAnalyzer:
    def __init__(self):
        self.connections = []
        self.stats = defaultdict(int)

    def get_connections(self):
        """Get current network connections"""
        try:
            result = subprocess.run(['netstat', '-anp'], 
                                  capture_output=True, text=True)
            return result.stdout.split('\n')
        except Exception as e:
            print(f"Error getting connections: {e}")
            return []

    def parse_connections(self, lines):
        """Parse netstat output"""
        connections = []

        for line in lines:
            if 'tcp' in line or 'udp' in line:
                parts = line.split()
                if len(parts) >= 6:
                    connection = {
                        'protocol': parts[0],
                        'local_address': parts[3],
                        'remote_address': parts[4],
                        'state': parts[5] if len(parts) > 5 else 'N/A',
                        'process': parts[6] if len(parts) > 6 else 'N/A'
                    }
                    connections.append(connection)

        return connections

    def analyze_connections(self):
        """Analyze network connections"""
        lines = self.get_connections()
        self.connections = self.parse_connections(lines)

        # Count by protocol
        protocols = Counter(conn['protocol'] for conn in self.connections)

        # Count by state
        states = Counter(conn['state'] for conn in self.connections)

        # Count by remote IP
        remote_ips = Counter(
            conn['remote_address'].split(':')[0] 
            for conn in self.connections 
            if ':' in conn['remote_address']
        )

        # Count by local port
        local_ports = Counter(
            conn['local_address'].split(':')[-1] 
            for conn in self.connections 
            if ':' in conn['local_address']
        )

        return {
            'total_connections': len(self.connections),
            'protocols': dict(protocols),
            'states': dict(states),
            'top_remote_ips': dict(remote_ips.most_common(10)),
            'top_local_ports': dict(local_ports.most_common(10))
        }

    def detect_anomalies(self):
        """Detect potential security issues"""
        anomalies = []

        # Check for excessive connections from single IP
        remote_ips = Counter(
            conn['remote_address'].split(':')[0] 
            for conn in self.connections 
            if ':' in conn['remote_address'] and not conn['remote_address'].startswith('127.')
        )

        for ip, count in remote_ips.items():
            if count > 50:  # Threshold for suspicious activity
                anomalies.append(f"High connection count from {ip}: {count}")

        # Check for unusual ports
        unusual_ports = ['1234', '4444', '5555', '6666', '7777', '8888', '9999']
        for conn in self.connections:
            for port in unusual_ports:
                if f":{port}" in conn['remote_address']:
                    anomalies.append(f"Connection to unusual port {port}: {conn['remote_address']}")

        return anomalies

    def generate_report(self):
        """Generate comprehensive report"""
        analysis = self.analyze_connections()
        anomalies = self.detect_anomalies()

        report = {
            'timestamp': datetime.now().isoformat(),
            'analysis': analysis,
            'anomalies': anomalies,
            'recommendations': self.get_recommendations(analysis, anomalies)
        }

        return report

    def get_recommendations(self, analysis, anomalies):
        """Generate security recommendations"""
        recommendations = []

        if analysis['total_connections'] > 1000:
            recommendations.append("High connection count detected - monitor for potential DDoS")

        if len(anomalies) > 0:
            recommendations.append("Security anomalies detected - investigate immediately")

        if 'SYN_RECV' in analysis['states'] and analysis['states']['SYN_RECV'] > 100:
            recommendations.append("High SYN_RECV count - potential SYN flood attack")

        return recommendations

def main():
    analyzer = ConnectionAnalyzer()
    report = analyzer.generate_report()

    print(json.dumps(report, indent=2))

    # Save report to file
    with open(f"network_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json", 'w') as f:
        json.dump(report, f, indent=2)

if __name__ == "__main__":
    main()

Surveillance de la performance

Performance de connexion

# Monitor connection establishment rate
watch -n 1 'netstat -s | grep "connections established"'

# Monitor TCP retransmissions
netstat -s | grep -i retrans

# Monitor packet drops
netstat -s | grep -i drop

# Monitor buffer usage
netstat -s | grep -i buffer

Surveillance de la largeur de bande

# Monitor interface throughput
watch -n 1 'netstat -i | grep -v "Kernel\|Iface\|lo"'

# Calculate bandwidth utilization
netstat -i | awk 'NR>2 && $1!="lo" {
    rx_bytes=$3; tx_bytes=$7;
    print $1, "RX:", rx_bytes, "TX:", tx_bytes
}'

# Monitor network statistics
netstat -s | grep -E "(packets|bytes)"

Utilisation des ressources du système

# Monitor socket usage
netstat -s | grep -i socket

# Check for memory issues
netstat -s | grep -i memory

# Monitor connection limits
ulimit -n  # Check file descriptor limit
cat /proc/sys/net/core/somaxconn  # Check socket backlog limit

Dépannage

Questions communes

Nombre de connexions élevées

# Identify processes with most connections
netstat -anp | awk '{print $7}' | sort | uniq -c | sort -nr | head -10

# Check for connection leaks
netstat -an | grep TIME_WAIT | wc -l

# Monitor connection states over time
watch -n 5 'netstat -an | awk "{print \$6}" | sort | uniq -c'

Questions relatives à la liaison des ports

# Check if port is already in use
netstat -ln | grep :80

# Find process using specific port
netstat -lnp | grep :80

# Check for port conflicts
netstat -ln | sort -k4

Problèmes de connectivité réseau

# Check routing table
netstat -rn

# Verify interface status
netstat -i

# Check for dropped packets
netstat -i | grep -v "0.*0.*0.*0"

# Monitor interface errors
watch -n 1 'netstat -i | awk "NR>2 {print \$1, \$4, \$8}"'

Commandes diagnostiques

# Comprehensive network state dump
netstat -anp > netstat_full.txt

# Quick connection summary
netstat -s | head -20

# Check for unusual activity
netstat -an | grep -v "127.0.0.1\|::1" | grep ESTABLISHED

# Monitor real-time changes
watch -d -n 1 'netstat -tulpn | head -20'

Optimisation des performances

# Tune TCP parameters (Linux)
echo 'net.core.somaxconn = 65535' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_max_syn_backlog = 65535' >> /etc/sysctl.conf
echo 'net.core.netdev_max_backlog = 5000' >> /etc/sysctl.conf

# Apply changes
sysctl -p

# Monitor the effect
netstat -s | grep -i listen

Meilleures pratiques

Pratiques exemplaires en matière de sécurité

# Regular security audits
netstat -ln | grep -v "127.0.0.1\|::1" > listening_services.txt

# Monitor for unauthorized services
diff previous_services.txt current_services.txt

# Check for backdoors
netstat -anp | grep -E ":(1234|4444|5555|6666|7777|8888|9999)"

# Verify expected services only
netstat -lnp | awk '{print $4, $7}' | sort

Surveillance des meilleures pratiques

# Automated monitoring
*/5 * * * * /usr/local/bin/network_monitor.sh

# Log rotation for network logs
logrotate -f /etc/logrotate.d/network

# Baseline establishment
netstat -anp > /var/baseline/network_baseline_$(date +%Y%m%d).txt

# Regular comparison
diff /var/baseline/network_baseline_*.txt current_state.txt

Meilleures pratiques en matière de rendement

# Use ss instead of netstat for better performance
ss -tulpn

# Limit output for large systems
netstat -an | head -100

# Use specific filters
netstat -tn | grep :80

# Avoid DNS resolution in scripts
netstat -n

Documentation Meilleures pratiques

# Document network configuration
netstat -rn > network_routes.txt
netstat -i > network_interfaces.txt
netstat -ln > listening_services.txt

# Create network inventory
netstat -anp | awk '{print $7}' | sort | uniq > network_processes.txt

# Regular snapshots
mkdir -p /var/log/network_snapshots
netstat -anp > "/var/log/network_snapshots/netstat_$(date +%Y%m%d_%H%M%S).txt"

Exemples d'intégration

SIEM Intégration

# Syslog format for SIEM
netstat -anp | logger -t netstat -p local0.info

# JSON format for modern SIEM
netstat -anp | awk '{print "{\"timestamp\":\"" strftime("%Y-%m-%d %H:%M:%S") "\",\"connection\":\"" $0 "\"}"}'

# Send to remote syslog
netstat -anp | logger -n siem.company.com -P 514 -t netstat

Suivi de l'intégration

# Prometheus metrics format
echo "network_connections_total $(netstat -an | wc -l)" | curl -X POST http://pushgateway:9091/metrics/job/netstat

# Nagios check
if [ $(netstat -an | wc -l) -gt 1000 ]; then
    echo "CRITICAL - Too many connections"
    exit 2
fi

Intégration de l'automatisation

# Ansible playbook task
- name: Check network connections
  shell: netstat -anp
  register: netstat_output

# Terraform provisioner
provisioner "local-exec" {
  command = "netstat -ln > network_state.txt"
}

Résumé

Netstat est un outil de diagnostic réseau essentiel qui fournit des informations complètes sur les connexions réseau, les tables de routage et les statistiques d'interface. Les principales capacités sont les suivantes :

  • Surveillance de la connexion: Suivre les connexions TCP/UDP et leurs états
  • Identification du processus: Connexions réseau à des processus spécifiques
  • Analyse de la sécurité: Détecter les activités suspectes du réseau et les menaces potentielles
  • Surveillance du rendement: Analyser les performances du réseau et identifier les goulets d'étranglement
  • Dépannage: Diagnostiquer les problèmes de connectivité réseau et de configuration

Pour les systèmes modernes, envisager d'utiliser ss (statistiques de poche) comme alternative plus rapide à netstat, en particulier pour les environnements à grande échelle. Une surveillance et une analyse régulières des connexions réseau sont essentielles au maintien de la sécurité et des performances du système.