scripts/bashrc.d/networks.sh
2024-08-14 17:33:34 +02:00

92 lines
2.7 KiB
Bash

#!/bin/bash
# Définir les réseaux à exclure (séparés par des virgules)
netexclude="10.9.9.0/24,127.0.0.0/8,192.168.122.0/24"
# Convertir la liste des exclusions en un tableau
IFS=',' read -r -a exclude_array <<< "$netexclude"
# Fonction pour vérifier si une IP est dans la liste d'exclusions
function is_excluded {
local ip=$1
local ipnum
ipnum=$(printf "%d" "$(echo "$ip" | awk -F. '{ print ($1 * 16777216) + ($2 * 65536) + ($3 * 256) + $4 }')")
for net in "${exclude_array[@]}"; do
IFS='/' read -r net_addr net_mask <<< "$net"
local netnum
netnum=$(printf "%d" "$(echo "$net_addr" | awk -F. '{ print ($1 * 16777216) + ($2 * 65536) + ($3 * 256) + $4 }')")
local mask
mask=$(( 0xFFFFFFFF << (32 - net_mask) ))
if (( (ipnum & mask) == (netnum & mask) )); then
return 0
fi
done
return 1
}
# Récupérer les interfaces réseau actives
interfaces=$(ip -o link show | awk -F': ' '{print $2}')
# Définir les variables pour les réseaux
declare -A net_info
net_count=0
for intf in $interfaces; do
# Obtenir l'adresse IP de l'interface
ip_addr=$(ip -o -4 addr list $intf | awk '{print $4}')
ip_only=$(echo $ip_addr | cut -d/ -f1)
# Vérifier si l'adresse IP est dans la liste des exclusions
if is_excluded "$ip_only"; then
continue
fi
if [[ ! -z $ip_addr ]]; then
net_count=$((net_count + 1))
net_info["net${net_count}_ip"]=$ip_only
net_info["net${net_count}_mask"]=$(ip -o -4 addr show $intf | awk '{print $4}' | cut -d/ -f2)
net_info["net${net_count}_gw"]=$(ip route | grep -w "$intf" | grep -oP 'via \K[^ ]+')
net_info["net${net_count}_net"]=$(ip route | grep -w "$intf" | grep -oP '\b(\d{1,3}\.){3}\d{1,3}/\d{1,2}\b')
if [[ $net_count -ge 4 ]]; then
break
fi
fi
done
# Afficher les résultats et définir les variables globales
for i in $(seq 1 $net_count); do
echo "Réseau $i:"
echo "IP: ${net_info[net${i}_ip]}"
echo "Masque: ${net_info[net${i}_mask]}"
echo "Passerelle: ${net_info[net${i}_gw]}"
echo "Réseau: ${net_info[net${i}_net]}"
echo ""
export "net${i}ip=${net_info[net${i}_ip]}"
export "net${i}mask=${net_info[net${i}_mask]}"
export "net${i}gw=${net_info[net${i}_gw]}"
export "net${i}net=${net_info[net${i}_net]}"
done
# Définir les variables globales
if [[ ! -z ${net_info[net1_ip]} ]]; then
export net1=${net_info[net1_ip]}
fi
if [[ ! -z ${net_info[net2_ip]} ]]; then
export net2=${net_info[net2_ip]}
fi
if [[ ! -z ${net_info[net3_ip]} ]]; then
export net3=${net_info[net3_ip]}
fi
if [[ ! -z ${net_info[net4_ip]} ]]; then
export net4=${net_info[net4_ip]}
fi
echo "DEBUG net1=$net1"
echo "DEBUG net2=$net2"