Script que identifica na rede a existência de duplicidades de IPs e MACs que utilizam mais de um IP

Publicado por Perfil removido 12/01/2009

[ Hits: 7.771 ]

Download script.rede.tar.gz




Este script mantém uma lista com "IP;MAC;data de acesso" dos IPs/MACs de sua rede.

Com base nesta lista ele verifica a existência de casos em que um IP é utilizado por mais de um MAC (IP duplicado) e casos em que um MAC utiliza mais de um IP (MACs espertinhos). PARA O CORRETO FUNCIONAMENTO DO SCRIPT É FUNDAMENTAL QUE LEIA O ARQUIVO LEIA-ME.txt

Obs.: Toda a estrutura do script está em um arquivo ".tar.gz". Para extraí-lo utilize o seguinte comando:

tar -xzf script.rede.tar.gz

Boa sorte!
Magnos

  



Esconder código-fonte

###>>> Arquivo de configuração "sepll.conf"
#################### ATENÇÃO !!! ########################
# NÃO APAGUE OU ALTERE O CONTEÚDO CONTIDO ANTES DO '='  #
# ##################################################### #

####-- Pastas e Arquivos --####
#- Lista de IPs e MACs duplicados/duplicadores
duplicidades=~/DUPLICIDADES.txt
#
#- Lista das conexões realizadas pelos MACs e IPs associados em cada conexão
listaIPmacDATA=~/ip.mac.data.txt
#
#- Pasta dos arquivos temporários
tmp=/tmp/rede.script
#
####-----------------------####
#
#
#- Determina o limite de tempo (em dias) que um IP;MAC permanece na lista de IPs e MACs (listaIPmacDATA)
# Ou seja, caso um IP/MAC não se conecte a rede dentro deste limite de tempo, a linha do mesmo é removida.
# TEMPO EM DIAS !!!
tempo=90



##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$



###>>> Script mestre "spell.sh"


#!/bin/bash
##################-- Arquivo de Configuração --######################
config='spell.conf' #
#####################################################################
######## Obtenção de pastas arquivos e scripts a partir do arquivo de configuração #########
###- Scripts -###
acessos=scripts/list.update/acessos.sh
rmold=scripts/list.update/rm.old.sh
duplicidade=scripts/duplicidade/duplicidade.sh
montalista=scripts/duplicidade/monta.lista.sh
###-----------###
###- Variaveis -###
tempo=$(grep -iw ^'tempo' $config | awk -F '=' '{print $2}')
###-------------###
###- Arquivos
duplicidades=$(grep -iw ^'duplicidades' $config | awk -F'=' '{print $2}')
listaIPmacDATA=$(grep -iw ^'listaIPmacDATA' $config | awk -F'=' '{print $2}')
###- Pastas
tmp=$(grep -iw ^'tmp' $config | awk -F'=' '{print $2}')
############################################################################################
test -e $listaIPmacDATA
h=$?
if [ "$h" = '1' ]; then
echo 'a: Lista todos IPs e MACs relacionados, inclusive as datas e horas de acesso.' >$listaIPmacDATA
echo 'b: Voce pode fazer uma manutencao aqui, removendo linhas de IP;mac;data quando o mesmo não se conecta a tempo.' >>$listaIPmacDATA
echo 'c: Isto ajuda a manter uma lista de duplicidade de IPs atualizada e portanto mais confiavel.' >>$listaIPmacDATA
echo 'd: Evitando que duplicidades antigas continuem sendo incluidas na lista de duplicidades.' >> $listaIPmacDATA
echo 'e: IP ; MAC ; Data e hora do último acesso.' >> $listaIPmacDATA
fi
################## Ações de Pasta #############
rm -rf $tmp #se o diretório já existir ele o apaga, para evitar problemas
mkdir -p $tmp
##########---------------------#################
############---- Execução de scripts -----------############
#- Atualiza a listaIPmacDATA 
sh $acessos $listaIPmacDATA $tmp
#- Remove da listaIPmacDATA IPs/MACs que não utilizaram a rede dentro do prazo estimado
sh $rmold $tempo $listaIPmacDATA $tmp
#- Faz a verificação de duplicidades e MAC espertinhos
sh $duplicidade $listaIPmacDATA $tmp
#- Monta a lista de duplicidades, listando os IPs duplicados e os MACs espertinhos
sh $montalista $duplicidades $tmp
############------------------------------------############
###-- Deleta pasta de arquivos temporária
rm -rf $tmp



##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$



###>>>acessos.sh


#!/bin/bash
#Arquivos de configuração:
#IPs duplicados
###################################################################################
###- Arquivos e Pastas
listaIPmacDATA=$1
tmp=$2
######################
dupIP="$duplicados/ip"
dupMAC="$duplicados/mac"
arptemp="$tmp/ip.mac.txt"
arptmp="$tmp/ip.mac.data.txt"
sedtmp="$tmp/sed.tmp"
sorttmp="$tmp/sorto.ip.mac.data.txt"
###################################################################################
###################################################################################
echo -n 'Procurando IPs e MACs conectados a rede: isto pode demorar um pouco...'
arp -a | awk '{print $2,$4}' > $arptemp
while read line ; do
ip=$(echo $line | egrep -wo "(((([0-9]{1,3})\.){3})[0-9]{1,3})")
mac=$(echo $line | egrep -wio "((([0-9a-z]{2}):){5}[0-9a-z]{2})")
macExiste=$(echo $mac | awk -F':' '{print $3}')
if [ -n "$macExiste" ]; then # define acoes caso o MAC esteja "oculto"
echo "$ip;$mac">>$arptmp
else
echo "$ip;MACoculto">>$arptmp
fi
done <$arptemp
echo 'Concluido!'
###################################################################################
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
echo -n 'Atualizando lista de acessos (ip.mac.data.txt): '
while read ipMAC ; do
###################################################################################
###- Variaveis
ip=$(echo $ipMAC | awk -F';' '{print $1}')
mac=$(echo $ipMAC | awk -F';' '{print $2}')
acesso=$(date +%d-%m-%Y+%T)
###################################################################################
###################################################################################
### Testa se a linha IP;MAC está na lista d ip;mac
a=$(grep -wic "$ip;$mac" "$listaIPmacDATA") #conta o numero de linhas com ip;mac
###----------------------------------------------------
### Se $a nulo, adiciona linha ip;mac, se não nulo atualiza a data de acesso
if [ "$a" -lt '1' ]; then
echo "$ip;$mac;$acesso" >>"$listaIPmacDATA"
else
acessoold=$(grep -iw "$ip;$mac" $listaIPmacDATA | awk -F';' '{print $3}')
sed -e "s/$ip;$mac;$acessoold/$ip;$mac;$acesso/g" $listaIPmacDATA >"$sedtmp" && mv -f "$sedtmp" "$listaIPmacDATA"
fi
###################################################################################
done < "$arptmp"
echo "Concluido!"
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sort -t . -k1,1n -k2,2n -k3,3n -k4,4n $listaIPmacDATA > $sorttmp && mv -f $sorttmp $listaIPmacDATA



##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$



###>>>rm.old.sh


#!/bin/bash
###- Este script remove da lista ip.mac.data.txt linhas (acossiações de IPs e MACs) que não se conectam a rede por um prazo
# de tempo estipulado em spell.conf
###- Arquivos
tempo=$1
listaIPmacDATA=$2
tmp=$3
listaIPmacDATAtmp="$tmp/rm.old.sh.ip.mac.data.tmp"
sedlistatmp="$tmp/sed.ip.mac.data.tmp"
###################
##- Data atual
ano=$(date +%Y)
mes=$(date +%m)
dia=$(date +%d)
##--------------
###- Passa todas as linha com IPs e MACs para listaIPmacDATAtmp
egrep -w "(((([0-9]{1,3})\.){3})[0-9]{1,3})" $listaIPmacDATA >$listaIPmacDATAtmp
###------------------
while read linha ; do
acesso=$(echo $linha | awk -F';' '{print $3}') # ultimo acesso do IP/MAC
###- Identifica qual foi a ultima vez que ouve a conexão de ip;mac em listaIPmacDATA
acessoano=$(echo $linha | awk -F';' '{print $3}' | awk -F'+' '{print $1}' | awk -F'-' '{print $3}')
acessomes=$(echo $linha | awk -F';' '{print $3}' | awk -F'+' '{print $1}' | awk -F'-' '{print $2}')
acessodia=$(echo $linha | awk -F';' '{print $3}' | awk -F'+' '{print $1}' | awk -F'-' '{print $1}')
###-------------------------
###- Calcula o numero de dias a partir da ultima conexão
diasatual=$((($ano*365)+($mes*30)+$dia))
diasacesso=$((($acessoano*365)+($acessomes*30)+$acessodia))
dias=$(($diasatual-$diasacesso))
###- Se o numero de dias for superior ao determinado em spell.conf, deleta a linha especifica em listaIPmacDATA
if [ "$dias" -ge "$tempo" ]; then
ip=$(echo $linha | awk -F';' '{print $1}')
mac=$(echo $linha | awk -F';' '{print $2}')
sed -e "/$ip;$mac;$acesso/d" $listaIPmacDATA >$sedlistatmp && mv -f $sedlistatmp $listaIPmacDATA 
fi
###----------------------------
done <$listaIPmacDATAtmp



##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$



###>>>duplicidade.sh


#!/bin/bash
###################################################################################
###- Arquivos e Pastas
listaIPmacDATA=$1
tmp=$2
######################
duplicados="$tmp/duplicados"
dupIP="$duplicados/ip"
dupMAC="$duplicados/mac"
listaIP="$tmp/ips.txt"
listaMAC="$tmp/macs.txt"
###################################################################################
mkdir -p $duplicados
mkdir -p $dupIP
mkdir -p $dupMAC
###################################################################################
####-- Cria uma lista com todos os IPs contidos em lista.IP.mac.DATA
egrep -wo "(((([0-9]{1,3})\.){3})[0-9]{1,3})" $listaIPmacDATA | sort -t . -k1,1n -k2,2n -k3,3n -k4,4n | uniq >$listaIP
###################################################################################
###################################################################################
####-- Cria uma lista com todos os MACs contidos em lista.IP.mac.DATA
egrep -wio "((([0-9a-z]{2}):){5}[0-9a-z]{2})" $listaIPmacDATA | sort -t : -k1,1 -k2,2 -k3,3 -k4,4 -k5,5 -k6,6 | uniq >$listaMAC
###################################################################################
###################################################################################
###- Verifica a existência de duplicidades de IPs
echo -n "Verificando a existencia de duplicidade de IPs: "
while read ip ; do
###- Conta o número de MACs que já utilizaram o IP
b=$(grep -wc "$ip" "$listaIPmacDATA")
###----------------------------------------------------
### Se o número de MACs que já utilizaram o IP é maior que 1, lista os MACs e as datas de acesso
if [ "$b" -gt '1' ]; then
echo "O IP: $ip já foi utilizado pelos seguintes MACs:">"$dupIP"/"$ip"
grep -w $ip $listaIPmacDATA | awk -F';' '{print $2,$3}'>>"$dupIP"/"$ip"
fi
done <$listaIP
echo "Concluido!"
###################################################################################
###################################################################################
###- Verifica e existência de MACs espertinhos
echo -n "Verificando a existencia de MACs espertinhos: "
while read mac ; do
###- Conta o número de IPs que o MAC já utilizou
c=$(grep -wc "$mac" "$listaIPmacDATA")
###---------------------------------------------------
### Se o número de IPs que o MAC já utilizou é maior que 1, lista os IPs e datas de acesso
if [ "$c" -gt "1" ]; then
echo "O MAC: $mac já utilizou os seguintes IPs: ">"$dupMAC"/"$mac"
grep -wi "$mac" "$listaIPmacDATA" | awk -F';' '{print $1,$3}' >>"$dupMAC"/"$mac"
fi
done <$listaMAC
echo "Concluido!"
###################################################################################



##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$



###>>>monta.lista.sh


#!/bin/bash
###########################################################################
duplicidades=$1
tmp=$2
####---
duplicados="$tmp/duplicados"
dupIP="$duplicados/ip"
dupMAC="$duplicados/mac"
###########################################################################
###########################################################################
rm -f $duplicidades
###########################################################################
###########################################################################
#- conta o número de arquivos de IPs duplicados
nIPs=$(ls -Blt $dupIP | cat -n | awk '{print $1}' | tail -1)
#----------------------------------------------
if [ "$nIPs" -gt '1' ]; then # se o diretório não estiver vazio, executa os comandos
a=2
echo -n 'Montando lista de IPs duplicados: '
while [ "$a" -le "$nIPs" ]; do
ip=$(ls -Bl $dupIP | awk '{print $8}' | head -$a | tail -1)
echo ' '>>$duplicidades
echo '$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$'>>$duplicidades
cat $dupIP/$ip>>$duplicidades
a=$(($a+1))
done
echo 'Concluído!'
fi
###########################################################################
###########################################################################
#- conta o número de arquivos de MACs duplicadores
nMACs=$(ls -Blt $dupMAC | cat -n | awk '{print $1}' | tail -1)
#----------------------------------------------
if [ "$nMACs" -gt '1' ]; then # se o diretório não estiver vazio, executa os comandos
a=2
echo -n 'Montando lista de MACs espertinhos: '
while [ "$a" -le "$nMACs" ]; do
mac=$(ls -Bl $dupMAC | awk '{print $8}' | head -$a | tail -1)
echo ' '>>$duplicidades
echo '$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$'>>$duplicidades
cat $dupMAC/$mac>>$duplicidades
a=$(($a+1))
done
echo 'Concluido!'
fi
###########################################################################

Scripts recomendados

Tabela de cores em shellscript

Criação de unidades criptografadas

Script de compilação do Xorg 7.2 otimizado para Slackware 64 bits (Slamd64)

Compilar OpenSSL

POSTFIX AUTOMÁTICO COM MYSQL E IPTABLES - APAGANDO MSG ANTIGAS


  

Comentários

Nenhum comentário foi encontrado.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts