• Publicidad

Perl con comandos Linux netstat y awk

¿Eres administrador de sistemas? Este foro es para todos aquellos temas relacionados con el uso de Perl para administración de sistemas.

Perl con comandos Linux netstat y awk

Notapor jimr1984 » 2016-06-15 17:16 @761

SO: Centos

Comando ejecutado:

Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
  1. netstat -plan  | grep ":80" | awk '{print $5}' | cut -d ":" -f 1 | sort | uniq -c | sort -nk 1 | awk '{print $1"-"$2}'
Coloreado en 0.003 segundos, usando GeSHi 1.0.8.4


resultado:
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
1..........
2....
 20-190.186.38.13
25-200.105.185.159
27-181.114.119.34
35-186.167.244.224
40-190.102.144.100
40-190.186.216.195
45-107.167.106.145
46-190.180.5.136
52-181.114.123.176
53-181.51.100.15
53-65.55.185.254
75-186.121.250.114
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

Formato: totalconexiones-direcciónIP

Ejemplo: 75-186.121.250.114

Necesito guardar esto en un array en Perl y una función de Perl que se alimente de cada valor.

Ejemplo:

GeolocalizacionIP(@arrayip);

Resultado:
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
IP  65.55.185.254         PAIS  EEUU     CONEXIONES   53
IP  186.121.250.114       PAIS  CHINA    CONEXIONES   75
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4


Código:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. print " CONEXION ACTIVAS :   HTTP : 80  \n";
  2. print "============================================================================\n";
  3. my @var = `netstat -plan  | grep ":80" | awk '{print $5}' | cut -d ":" -f 1 | sort | uniq -c | sort -nk 1 | awk '{print $1":"$2}' `;
  4.  
  5. print "@var";
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4

Resultado:
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
============================================================================
:
:
:
:
:
:
:
:
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4
jimr1984
Perlero nuevo
Perlero nuevo
 
Mensajes: 123
Registrado: 2012-11-25 07:11 @341

Publicidad

Re: Perl con comandos Linux netstat y awk

Notapor explorer » 2016-06-18 19:11 @841

Perl puede hacer mucho mejor el trabajo que llamar a varios comandos que, quizás, no estén en el sistema en donde estemos.

Esta es mi versión:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. #
  3. # Conexiones externas
  4. #
  5.  
  6. use v5.14.2;
  7. use utf8;                                                       # este código está escrito en utf8
  8. use open IO => qw':utf8 :std';                                  # queremos que la salida también esté en utf8
  9.  
  10. use Geo::IP;                                                    # librería para resolver IP
  11. my $gi = Geo::IP->open("/usr/share/GeoIP/GeoIP.dat", GEOIP_STANDARD);
  12.  
  13. # Cuenta de IP remotas que se conectan a nosotros por el $puerto
  14. my $puerto = 80;
  15. my %ip_remotas;
  16.  
  17. for my $tcp (grep {/^tcp/}  qx(netstat -pan --tcp)) {           # Conexiones tcp
  18.  
  19.     my($local,$remoto) = (split " ", $tcp)[3,4];                # cuarta y quinta columnas
  20.  
  21.     if ($local =~ /\d:$puerto\b/) {                             # si hay una conexión por $puerto a IP local
  22.  
  23.         my($ip_remota)= $remoto =~ /^([\d.]+)/;                 # sacamos la IP remota
  24.        
  25.         next if $ip_remota eq '0.0.0.0';                        # si es el servidor local, no nos interesa
  26.        
  27.         $ip_remotas{$ip_remota}++;                              # y la contabilizamos
  28.     }
  29. }
  30.  
  31. # salida ordenada por el número de conexiones a IP remotas, en orden numérico inverso
  32. say "  CONEXIONES ACTIVAS A $puerto";
  33. say "=" x 30;
  34.  
  35. my $total_con = 0;
  36. my $total_ip  = 0;
  37.  
  38. for my $ip (sort {$ip_remotas{$b} <=> $ip_remotas{$a}} keys %ip_remotas) {
  39.  
  40.     my $pais = uc $gi->country_name_by_addr($ip);
  41.     my $num  = $ip_remotas{$ip};
  42.  
  43.     say sprintf "IP  %-20s  PAÍS  %-20s  CONEXIONES  %d", $ip, $pais, $num;
  44.    
  45.     $total_con += $num;
  46.     $total_ip++;
  47. }
  48.  
  49. say "TOT $total_ip                                                            $total_con";
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4

Observando el código, con cambiar el valor de $puerto podemos vigilar otro tipo de conexiones.
Ejemplo de salida:
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
  CONEXIONES ACTIVAS A 80
==============================
IP  181.67.9.239          PAÍS  PERU                  CONEXIONES  6
IP  188.77.225.159        PAÍS  SPAIN                 CONEXIONES  2
IP  186.156.13.173        PAÍS  CHILE                 CONEXIONES  2
IP  192.243.55.136        PAÍS  UNITED STATES         CONEXIONES  2
IP  66.249.64.239         PAÍS  UNITED STATES         CONEXIONES  1
IP  66.249.75.250         PAÍS  UNITED STATES         CONEXIONES  1
IP  192.243.55.130        PAÍS  UNITED STATES         CONEXIONES  1
IP  66.249.64.183         PAÍS  UNITED STATES         CONEXIONES  1
IP  66.249.64.244         PAÍS  UNITED STATES         CONEXIONES  1
IP  87.222.98.199         PAÍS  SPAIN                 CONEXIONES  1
IP  66.249.64.212         PAÍS  UNITED STATES         CONEXIONES  1
IP  192.243.55.133        PAÍS  UNITED STATES         CONEXIONES  1
TOT 12                                                            20
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

La librería Geo::IP permite acceder a los archivos GeoIP que publica la empresa maxmind.com, que permite convertir las IP a países, regiones o incluso ciudades.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14475
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España


Volver a Administración

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 0 invitados

cron