• Publicidad

Comando ping

¿Apenas comienzas con Perl? En este foro podrás encontrar y hacer preguntas básicas de Perl con respuestas aptas a tu nivel.

Comando ping

Notapor academico69 » 2012-06-12 19:43 @863

Recién hace dos días que arranco con esto, así que perdonen si pregunto alguna boludez o algo muy sencillo :oops:

Mi consulta es la siguiente:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use Shell;
  3. print "Content-type: text/html\n\n";
  4.  
  5. $foo = ping("-c5", "www.google.com\n\n");
  6. print $foo;
  7.  
  8.  
  9.  
  10. $foo1 = ping("-c5", "www.ole.com.ar\n\n");
  11. print $foo1;
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4


Yo tengo armado esta función para tirar ping a esas dos páginas, pero al ejecutar esto vía web,
http://miservidor.com.ar/cgi-bin/perl.pl

El ping me aparece de corrido sin salto de línea, ocupando toda la pantalla de la web y me gustaría poder ordenarlo, por las bases que tengo de programación no precisamente en Perl, pensé en llamar a un sub-procedimiento y ordenarlo para después hacerle el print(), pero la verdad que no le agarré mucho la mano de cómo hacerlo.

Gracias.
Última edición por explorer el 2012-06-13 02:30 @146, editado 1 vez en total
Razón: Marcas de código Perl
academico69
Perlero nuevo
Perlero nuevo
 
Mensajes: 3
Registrado: 2012-06-12 19:27 @852

Publicidad

Re: Comando ping

Notapor explorer » 2012-06-13 05:45 @281

Bienvenido a los foros de Perl en Español, academico69.

Recuerda que lo que estás sacando hacia la página web es (o debe ser) código HTML, así que los retornos de carro "\n" no son suficientes para indicarle al navegador web que debe hacer saltos de línea.

Debes cambiar los "\n" por '<br>', que son las marcas HTML que indican la ruptura de línea (salto de línea).

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use Shell;
  3. print "Content-type: text/html\n\n";
  4.  
  5. my $ping;
  6.  
  7. $ping = ping('-c5', 'www.google.com');     # ¡Ping!
  8.  
  9. $ping =~ s/\n/<br>/g;                      # sustituimos todos los "\n" por '<br>'
  10.  
  11. print $ping;
  12.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

Entonces sale algo como esto:
PING www-cctld.l.google.com (173.194.34.248) 56(84) bytes of data.<br>64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=1 ttl=56 time=470 ms<br>64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=2 ttl=56 time=490 ms<br>64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=3 ttl=56 time=458 ms<br>64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=4 ttl=56 time=520 ms<br>64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=5 ttl=56 time=465 ms<br><br>--- www-cctld.l.google.com ping statistics ---<br>5 packets transmitted, 5 received, 0% packet loss, time 4000ms<br>rtt min/avg/max/mdev = 458.043/481.198/520.888/22.612 ms<br>

A esto le faltan cosas, y además, quedaría mejor si la salida quedara formateada, aunque no se viera directamente en el navegador.

Mejor así:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use Shell;
  3. print "Content-type: text/html\n\n";
  4.  
  5. print "<html>\n";                          # inicio de código HTML
  6. print "<body>\n";
  7.  
  8. my $ping;
  9.  
  10. $ping = ping('-c5', 'www.google.com');     # ¡Ping!
  11.  
  12. $ping =~ s/\n/<br>\n/g;                    # sustituimos todos los "\n" por "<br>\n"
  13.  
  14. print $ping;
  15.  
  16. print "</body>\n";                         # fin de código HTML
  17. print "</html>\n";
  18.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

Aquí le hemos añadido marcas HTML al principio y al final, y retornos de carro después de los '<br>'. La salida es así:
Sintáxis: [ Descargar ] [ Ocultar ]
Using html4strict Syntax Highlighting
  1. <html>
  2. <body>
  3. PING www-cctld.l.google.com (173.194.34.248) 56(84) bytes of data.<br>
  4. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=1 ttl=56 time=524 ms<br>
  5. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=2 ttl=56 time=533 ms<br>
  6. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=3 ttl=56 time=459 ms<br>
  7. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=4 ttl=56 time=419 ms<br>
  8. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=5 ttl=56 time=500 ms<br>
  9. <br>
  10. --- www-cctld.l.google.com ping statistics ---<br>
  11. 5 packets transmitted, 5 received, 0% packet loss, time 4004ms<br>
  12. rtt min/avg/max/mdev = 419.477/487.511/533.800/42.606 ms<br>
  13. </body>
  14. </html>
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
que ya tiene aspecto de página web...

Otra opción, en lugar de hacer la sustitución, es la de hacer la presentación de la salida de ping dentro de unas marcas <pre>, indicando que se trata de un texto que ya está preformateado, por lo que el navegador lo mostrará -generalmente- en fuente monoespaciada y respetando los avances de línea:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use Shell;
  3. print "Content-type: text/html\n\n";
  4.  
  5. print "<html>\n";                          # inicio de código HTML
  6. print "<body>\n";
  7.  
  8. my $ping = ping('-c5', 'www.google.com');  # ¡Ping!
  9.  
  10. $ping = "<pre>$ping</pre>";                # metemos al $ping dentro de las marcas <pre>
  11.  
  12. print $ping;
  13.  
  14. print "</body>\n";                         # fin de código HTML
  15. print "</html>\n";
  16.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
Y ya queda una salida más limpia:
Sintáxis: [ Descargar ] [ Ocultar ]
Using html4strict Syntax Highlighting
  1. <html>
  2. <body>
  3. <pre>PING www-cctld.l.google.com (173.194.34.248) 56(84) bytes of data.
  4. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=1 ttl=56 time=524 ms
  5. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=2 ttl=56 time=533 ms
  6. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=3 ttl=56 time=459 ms
  7. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=4 ttl=56 time=419 ms
  8. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=5 ttl=56 time=500 ms
  9.  
  10. --- www-cctld.l.google.com ping statistics ---
  11. 5 packets transmitted, 5 received, 0% packet loss, time 4004ms
  12. rtt min/avg/max/mdev = 419.477/487.511/533.800/42.606 ms
  13. </pre></body>
  14. </html>
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
Finalmente... está la opción de usar el módulo CGI de Perl, que abrevia buena parte del trabajo:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use CGI ':standard';
  3. use Shell;
  4.  
  5. my $ping = ping('-c5', 'www.google.com');  # ¡Ping!
  6.  
  7. print header();                            # Cabecera HTTP
  8. print start_html('Resultados del ping');   # inicio de página HTML, con su título
  9. print pre($ping);                          # marcas '<pre>'
  10. print end_html();                          # fin de código HTML
  11.  
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4
Y ya sale una respuesta completa:
Sintáxis: [ Descargar ] [ Ocultar ]
Using html4strict Syntax Highlighting
  1. Content-Type: text/html; charset=ISO-8859-1
  2.  
  3. <!DOCTYPE html
  4.        PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  5.         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  6. <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
  7. <head>
  8. <title>Resultado del ping</title>
  9. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  10. </head>
  11. <body>
  12. <pre>PING www-cctld.l.google.com (173.194.34.248) 56(84) bytes of data.
  13. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=1 ttl=56 time=341 ms
  14. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=2 ttl=56 time=394 ms
  15. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=3 ttl=56 time=276 ms
  16. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=4 ttl=56 time=289 ms
  17. 64 bytes from mad01s09-in-f24.1e100.net (173.194.34.248): icmp_seq=5 ttl=56 time=301 ms
  18.  
  19. --- www-cctld.l.google.com ping statistics ---
  20. 5 packets transmitted, 5 received, 0% packet loss, time 3998ms
  21. rtt min/avg/max/mdev = 276.630/320.739/394.159/42.664 ms
  22. </pre>
  23. </body>
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


Si quieres hacer pruebas, incluso lo puedes ejecutar desde la línea de comandos:
perl -MCGI=:standard -MShell -E '$ping = ping("-c5", "www.google.es"); print header(), start_html("Resultado del ping"), pre($ping), end_html();'
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Comando ping

Notapor academico69 » 2012-06-13 16:29 @729

La verdad, excelente. Probé todos los ejemplos que me diste, funciona bárbaro. Muchísimas gracias.

Ye hago otra consulta.

La salida en pantalla es esta:

Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
PING http://www.l.google.com (74.125.134.103) 56(84) bytes of data.
64 bytes from gg-in-f103.1e100.net (74.125.134.103): icmp_seq=1 ttl=47 time=154 ms
64 bytes from gg-in-f103.1e100.net (74.125.134.103): icmp_seq=2 ttl=48 time=153 ms
64 bytes from gg-in-f103.1e100.net (74.125.134.103): icmp_seq=3 ttl=48 time=153 ms
64 bytes from gg-in-f103.1e100.net (74.125.134.103): icmp_seq=4 ttl=48 time=154 ms
64 bytes from gg-in-f103.1e100.net (74.125.134.103): icmp_seq=5 ttl=48 time=153 ms

--- http://www.l.google.com ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4153ms
rtt min/avg/max/mdev = 153.267/153.844/154.665/0.730 ms
PING http://www.l.google.com (74.125.134.105) 56(84) bytes of data.
64 bytes from gg-in-f105.1e100.net (74.125.134.105): icmp_seq=1 ttl=47 time=154 ms
64 bytes from gg-in-f105.1e100.net (74.125.134.105): icmp_seq=2 ttl=47 time=153 ms
64 bytes from gg-in-f105.1e100.net (74.125.134.105): icmp_seq=3 ttl=46 time=156 ms
64 bytes from gg-in-f105.1e100.net (74.125.134.105): icmp_seq=4 ttl=47 time=154 ms
64 bytes from gg-in-f105.1e100.net (74.125.134.105): icmp_seq=5 ttl=47 time=153 ms

--- http://www.l.google.com ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4155ms
rtt min/avg/max/mdev = 153.227/154.411/156.383/1.233 ms
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4


Al finalizar cada ping, es decir, en el caso de que yo agregue más ping dentro del mismo script, ¿cómo separo entre ping y ping? ¿Hay un "\n" que no me está reemplazando por el <br> del final del ping? ¿O existe otra etiqueta?

CÓDIGO :


#!/usr/bin/perl
use Shell;
print "Content-type: text/html\n\n";

print "<html>\n";
print "<body>\n";

my $ping;

$ping = ping('-c5', 'www.google.com');

$ping =~ s/\n/<br>\n/g;

print $ping;




$ping2 = ping('-c5', 'www.google.com');

$ping2 =~ s/\n/<br>\n/g;

print $ping2;







print "</body>\n";
print "</html>\n";

Desde ya, muchas gracias. Excelentes respuestas.
academico69
Perlero nuevo
Perlero nuevo
 
Mensajes: 3
Registrado: 2012-06-12 19:27 @852

Re: Comando ping

Notapor explorer » 2012-06-13 17:35 @774

Podrías usar algo más visual, como por ejemplo, una línea horizontal:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use CGI ':standard';
  3. use Shell;
  4.  
  5. my @sites = qw(
  6.     www.google.com
  7.     www.ole.com.ar
  8. );
  9.  
  10. print header();                            # Cabecera HTTP
  11. print start_html('Resultados del ping');   # inicio de página HTML, con su título
  12.  
  13. for my $site (@sites) {
  14.     my $ping = ping('-c5', $site);         # ¡Ping!
  15.     print pre($ping);                      # pre-formateado
  16.     print hr;                              # regla horizontal
  17. }
  18.  
  19. print end_html();                          # fin de código HTML
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Comando ping

Notapor academico69 » 2012-06-13 17:45 @781

La verdad, me saco el sombrero, muy bueno.

Quedó excelente, te agradezco la ayuda, le voy tomando un poco la mano.


Saludos.
academico69
Perlero nuevo
Perlero nuevo
 
Mensajes: 3
Registrado: 2012-06-12 19:27 @852


Volver a Básico

¿Quién está conectado?

Usuarios navegando por este Foro: Google [Bot] y 4 invitados

cron