• Publicidad

Problema con Net::OpenSSH a Cisco

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

Re: Problema con Net::OpenSSH a Cisco

Notapor jero2528 » 2014-06-05 15:04 @669

Buenas tardes.

Respecto al tema, me pregunto si es posible ejecutar uno a uno cada comando, usando la estructura que me indicaste, salva anteriormente. Ahora, tratando de hacerlo así no me reconoce la siguiente sentencia:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. $ssh = -t Net::OpenSSH->new($ip, user => $user, passwd => $clave);
  2. if ($ssh->error) {
  3.        $stderr= -t $ssh->error;
  4.        warn "imposible conectar con servidor remoto $ip: ". $ssh->error;
  5.        return $stderr, $ssh;
  6. }
  7.  
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4

Estoy tratando con -t de hacer uso de un terminal para que funcione, pero me genera el error que relaciono a continuación:

Can't call method "error" on an undefined value at /usr/local/sc/libreria/misLibs.pl line 359 (que para mi caso la línea que indica el bash coincide con el if() citado anteriormente).

Agradezco me eches una mano de cómo puedo hacer uso del parámetro -t.

:)

Jero2528
Colombia
Saludos,

Jero2528
Avatar de Usuario
jero2528
Perlero nuevo
Perlero nuevo
 
Mensajes: 50
Registrado: 2014-05-14 15:43 @697
Ubicación: Bogota, Colombia

Publicidad

Re: Problema con Net::OpenSSH a Cisco

Notapor explorer » 2014-06-05 18:12 @800

Esto...

¿Sabes qué es lo que hace el operador '-t'?

Devuelve verdadero si el gestor o identificador de archivo que le sigue corresponde a una terminal tty.

Y resulta que lo estás aplicando a un objeto Net::OpenSSH... Me temo que eso no funcionará nunca.

El operador '-t' devuelve un valor de verdad, así que no lo estás usando adecuadamente.

¿Puedes explicar con más detalle qué es lo que quieres hacer?
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

Re: Problema con Net::OpenSSH a Cisco

Notapor jero2528 » 2014-06-09 09:07 @422

Hola, explorer/salva.

Quise resolverlo usando el parámetro -t pensando en que éste haría uso de un terminal para ejecutar comandos sobre el equipo remoto. Pero pasadas varias pruebas no funciona aún. ¿Podrían indicarme, por favor, cómo puedo hacer que me funcionen comandos usando SSH, bien sea OpenSSH o con Expect, o combinados mejor aún, con tal de que no requiera que le realice mucho cambios a una estructura como la que tengo a continuación?

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. ## -----------------------------------------------------------------------
  2.         # Así se realizarán las copias de seguridad de los equipos Cisco o Foundry
  3.         ## -----------------------------------------------------------------------
  4.         if (($type eq "Cisco") || ($type eq "Foundry")) {
  5.                 if (($ip eq 'X.X.X.X'))  {
  6.                         # La conexión a estos PIX es por ssh, no por telnet
  7.                         $ssh = Net::SSH::Expect->new (host => $ip, password=> $passbackupsdefault, user => 'admin', raw_pty => 1, ssh_option => " -c des ", timeout => 15);
  8.                         $ssh->login();
  9.                         $ssh->send("enable\n");
  10.                         $ssh->waitfor('Password:\s*\z', 5);
  11.                         $ssh->send("$passbackupsdefault");
  12.                         $ssh->waitfor('#', 5);
  13.                         $ssh->send("copy running-config tftp");
  14.                         $ssh->waitfor('Source', 5);
  15.                         $ssh->send("running-config");
  16.                         $ssh->waitfor('Address', 5);
  17.                         $ssh->send("$tftp_server");
  18.                         $ssh->waitfor('Destination', 5);
  19.                         $ssh->send("$file");
  20.                         $ssh->waitfor('ARBUENOC', 15);
  21.                         $ssh->close();
  22.                         $flag=1;
  23.                 } elsif (($ip eq 'X.X.X.X'))  {
  24.                         # La conexión a estos PIX es por ssh, no por telnet
  25.                         $ssh = Net::SSH::Expect->new (host => $ip, password=> $passbackupsdefault, user => $userbackupsdefault, raw_pty => 1, ssh_option => " -c des ", timeout => 15);
  26.                         $ssh->login();
  27.                         $ssh->send("enable\n");
  28.                         $ssh->waitfor('Password:\s*\z', 5);
  29.                         $ssh->send('miPasswordFast!');
  30.                         $ssh->waitfor('#', 5);
  31.                         $ssh->send("write net");
  32.                         $ssh->waitfor('#', 5);
  33.                         $ssh->close();
  34.                         `mv /tftpboot/tftpboot /tftpboot/$file`;
  35.                         $flag=1;
  36.                 ###################################################################################################
  37.                 ###### EL USO DE LOS IF  ANTERIORES YA EXISTÍA ANTES DE QUE YO TOMARA EL SCRIPT. POR ESO NO SÉ ####
  38.                 ###### CÓMO PUEDO COMBINAR OPENSSH CON EXPECT PARA REALIZAR LO QUE SIGUE A CONTINUACIÓN.       ####
  39.                 ###################################################################################################    
  40.                 } else {
  41.                         @conn1 = conectar_ssh($ip,$userbackupsdefault,$passbackupsdefault);
  42.                         if (($conn1[0])) {
  43.                                 $errores_1.="<br><font color='red'>Error01=$conn1[0]\n<br></font>";
  44.                         } else {
  45.                                 if (($ip eq 'X.X.X.X') || ($ip eq 'X.X.X.X'))  {
  46.                                         @out=$conn1[1]->capture({stdin_data =>"copy running-config tftp\n\n$tftp_server\n$file\n"});
  47.  
  48.                                 } else {
  49.                                         if ($ip =~ m/^10.16/) {
  50.                                                 @out=$conn1[1]->capture({stdin_data =>"terminal width 512\nterminal length 0\ncopy running-config tftp\n$tftp_server_p\n$file\n"});
  51.                                         } else {
  52.                                                 @out=$conn1[1]->capture({stdin_data =>"copy running-config tftp\n$tftp_server\n$file\n"});
  53.                                         }
  54.  
  55.                                 }
  56.                                 if (!($out[0])) {
  57.                                         $out[0] = "";
  58.                                 }
  59.                                 if (!($out[1])) {
  60.                                         $out[1] = "";
  61.                                 }
  62.                                 if (($out[0] =~ /'Not logged in'/) || ($out[0] =~ /error/) || ($out[1] =~ /error/)) {
  63.                                         $errores_2.="<br><font color='red'>Error02=Problemas al copiar la configuracion\n<br></font>";
  64.                                 } else {
  65.                                         $flag=1;
  66.                                         if ((($device_type eq 'Switch') || ($device_type eq 'Switch Principal Nodo')) && ($type eq "Cisco")) {
  67.                                                 if (($ip eq 'X.X.X.X') || ($ip eq 'X.X.X.X'))  {
  68.                                                         @out=$conn1[1]->capture({stdin_data =>"copy flash:vlan.dat tftp\n\n$tftp_server\n$filevlan\n"});
  69.  
  70.                                                 } else {
  71.                                                         @out=$conn1[1]->capture({stdin_data =>"copy flash:vlan.dat tftp\n$tftp_server\n$filevlan\n"});
  72.  
  73.                                                 }
  74.                                                 if (!($out[0])) {
  75.                                                         $out[0] = "";
  76.                                                 }
  77.                                                 if (!($out[1])) {
  78.                                                         $out[1] = "";
  79.                                                 }
  80.                                                 if (($out[0] =~ /'Not logged in'/) || ($out[0] =~ /error/) || ($out[1] =~ /error/)) {
  81.                                                         $errores_2.="<br><font color='red'>Error02=Problemas al copiar vlan.dat\n<br></font>";
  82.                                                 } else {
  83.                                                         $flagvlan=1;
  84.                                                 }
  85.                                         }
  86.                                 }
  87.                         }
  88.                 }
  89.                 sleep(20);
  90.                 if (!(-e "/tftpboot/$file") && ($flag == 1)) {
  91.                         $errores_3.="<br><font color='red'>Error03=Archivo vacio: /tftpboot/$file\n<br></font>";
  92.                 }
  93.                 if (!(-e "/tftpboot/$filevlan") && ($flagvlan == 1)) {
  94.                         $errores_3.="<br><font color='red'>Error03=Archivo vacio: /tftpboot/$filevlan\n<br></font>";
  95.                 }
  96.                         ## -----------------------------------------------------------------------
  97.         # Así se realizarán las copias de seguridad de los equipos Juniper
  98.         ## -----------------------------------------------------------------------
  99.         } elsif ($type eq "Juniper") {
  100.                 $filegz="$file.gz";
  101.                 @conn1 = conectar_ssh($ip,$userbackupsdefault,$passbackupsdefault);
  102.                 open (FILTER,"> /tftpboot/$filefilter");
  103.                 open (INTFILTER,"> /tftpboot/$fileinterfacesfilter");
  104.                 open (COS,"> /tftpboot/$filecos");
  105.                 open (CHASSIS,"> /tftpboot/$filechassis");
  106.                 open (ISIS,"> /tftpboot/$fileisis");
  107.                 if ($conn1[0]) {
  108.                         $errores_1.="<br><font color='red'>Error01=$conn1[0]\n<br></font>";
  109.                 } else {
  110.                         ## -----------------------------------------------------------------------
  111.                         #Se obtiene la información de configuración de CoS
  112.                         ## -----------------------------------------------------------------------
  113.                         @out=$conn1[1]->capture({stdin_data =>"show configuration class-of-service | display set | match interface | no-more"});
  114.                         print "show configuration class-of-service | display set | match interface | no-more\n";
  115.                         if (($out[0] =~ /Not logged in/) || ($out[0] =~ /error/) || ($out[1] =~ /error/)) {
  116.                                 $errores_2.="<br><font color='red'>Error02J01=Problemas al copiar la configuracion $out[0]\n<br></font>";
  117.                         } else {
  118.                                 foreach $line1 (@out) {
  119.                                         print COS "$line1";
  120.                                 }      
  121.                         }
  122.  
  123.                         ## -----------------------------------------------------------------------
  124.                         #Se obtiene la informacion de configuracion de los Filtros
  125.                         ## -----------------------------------------------------------------------
  126.                         @out=$conn1[1]->capture({stdin_data =>"show configuration firewall | display set | match filter | no-more"});
  127.                         print "show configuration firewall | display set | match filter | no-more\n";
  128.                         if (($out[0] =~ /Not logged in/) || ($out[0] =~ /error/) || ($out[1] =~ /error/)) {
  129.                                 $errores_2.="<br><font color='red'>Error02J02=Problemas al copiar la configuracion\n<br></font>";
  130.                         } else {
  131.                                 foreach $line1 (@out) {
  132.                                         print FILTER "$line1";
  133.                                 }      
  134.                         }
  135.  
  136.                         ## -----------------------------------------------------------------------
  137.                         #Se obtiene la informacion de configuracion de Interfaces con Filtros
  138.                         ## -----------------------------------------------------------------------
  139.                         @out=$conn1[1]->capture({stdin_data =>"show configuration interfaces | display set | match filter | no-more"});
  140.                         if (($out[0] =~ /Not logged in/) || ($out[0] =~ /error/) || ($out[1] =~ /error/)) {
  141.                                 $errores_2.="<br><font color='red'>Error02J03=Problemas al copiar la configuracion\n<br></font>";
  142.                         } else {
  143.                                 foreach $line1 (@out) {
  144.                                         print INTFILTER "$line1";
  145.                                 }      
  146.                         }
  147.  
  148.                         ## -----------------------------------------------------------------------
  149.                         #Se obtiene la informacion de configuracion de Interfaces con Filtros
  150.                         ## -----------------------------------------------------------------------
  151.                         @out=$conn1[1]->capture({stdin_data =>"show chassis fpc pic-status | display xml | no-more"});
  152.                         if (($out[0] =~ /Not logged in/) || ($out[0] =~ /error/) || ($out[1] =~ /error/)) {
  153.                                 $errores_2.="<br><font color='red'>Error02J04=Problemas al copiar la configuracion\n<br></font>";
  154.                         } else {
  155.                                 foreach $line1 (@out) {
  156.                                         if ((!($line1 =~ /master/)) ) {
  157.                                                 if ((!($line1 =~ /ebackups/)) ) {
  158.                                                         print CHASSIS "$line1";
  159.                                                 }
  160.                                         }
  161.                                 }      
  162.                         }
  163.  
  164.                         ## -----------------------------------------------------------------------
  165.                         #Se obtiene la informacion de configuracion de ISIS
  166.                         ## -----------------------------------------------------------------------
  167.                         @out=$conn1[1]->capture({stdin_data =>"show isis adjacency | display xml | no-more"});
  168.                         if (($out[0] =~ /Not logged in/) || ($out[0] =~ /error/) || ($out[1] =~ /error/)) {
  169.                                 $errores_2.="<br><font color='red'>Error02J05=Problemas al copiar la configuracion\n<br></font>";
  170.                         } else {
  171.                                 foreach $line1 (@out) {
  172.                                         if ((!($line1 =~ /master/)) ) {
  173.                                                 if ((!($line1 =~ /ebackups/)) ) {
  174.                                                         print ISIS "$line1";
  175.                                                 }
  176.                                         }
  177.                                 }      
  178.                         }
  179.  
  180.                         ## -----------------------------------------------------------------------
  181.                         #Se obtiene el archivo de backup como tal
  182.                         ## -----------------------------------------------------------------------
  183.                         if ($ip =~ m/^10.16/) {
  184.                                 @out=$conn1[1]->capture({stdin_data =>"file copy /config/juniper.conf.gz ftp://tftpconf:passForMakeBackups\@"."$tftp_server_p/$filegz"});
  185.                         } else {
  186.                                 @out=$conn1[1]->capture({stdin_data =>"file copy /config/juniper.conf.gz ftp://tftpconf:passForMakeBackups\@"."$tftp_server/$filegz"});
  187.                         }
  188.                         print "file copy /config/juniper.conf.gz ftp://tftpconf:passForMakeBackups\@"."$tftp_server/$filegz\n";
  189.                         sleep(10);
  190.                         if (($out[0] =~ /Not logged in/) || ($out[0] =~ /error/) || ($out[1] =~ /error/)) {
  191.                                 $errores_2.="<br><font color='red'>Error02J06=Problemas al copiar la configuracion\n<br></font>";
  192.                         } else {
  193.                                 $flag=1;
  194.                         }
  195.                
  196.                 }
  197.                 cerrar_ssh($conn1[1]);
  198.                 `/bin/gunzip /tftpboot/$filegz`;
  199.                 close (INTFILTER);
  200.                 close (FILTER);
  201.                 close (COS);
  202.                 close (CHASSIS);
  203.                 close (ISIS);
  204.  
Coloreado en 0.007 segundos, usando GeSHi 1.0.8.4

Es un poco extenso :) , y este es tan solo una parte del script y uno de los aproximadamente 70 scripts que requieren este cambio :roll:

Muchas gracias...
Saludos,

Jero2528
Avatar de Usuario
jero2528
Perlero nuevo
Perlero nuevo
 
Mensajes: 50
Registrado: 2014-05-14 15:43 @697
Ubicación: Bogota, Colombia

Re: Problema con Net::OpenSSH a Cisco

Notapor explorer » 2014-06-09 12:14 @551

Con el comando exec() de Net::SSH::Expect se puede ejecutar un comando en el sistema remoto y obtener la salida.

De otro modo, con Net::OpenSSH, enviando los datos por stdin, como se muestra en el programa, se obtiene la salida.

¿No es eso lo que quieres hacer?
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

Re: Problema con Net::OpenSSH a Cisco

Notapor jero2528 » 2014-06-09 16:56 @747

Sí, pero no funciona lo de OpenSSH; me genera el error que he comentado antes :(

jero2528 escribiste:Hola salva, muchas gracias, tenías razón, es por el tema de tener activo el debug, aun así lo comenté en el código, luego lo ejecuté y realiza la tarea sin problemas. Me llamó la atención el mensaje a continuación:

Pseudo-terminal will not be allocated because stdin is not a terminal.
Connection to 10.11.112.3 closed by remote host.
muxclient: master returned too much data (8 > 4)


Luego de que salió esa respuesta ejecuta normalmente los comandos. ¿Por qué sucede eso? ¿Debe preocuparme? ¿Es posible que falle? Si cambio por este código a todos mis scripts y lo ejecuto sobre equipos Juniper, ¿crees que funcionará?

Este es el código con el que probé:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. #####################################################################################
  3. # Jero2528
  4. # Marzo 2014
  5. #####################################################################################
  6.  
  7. use Net::OpenSSH;
  8. require '/usr/local/procedimientos.pl';
  9.  
  10. #$Net::OpenSSH::debug = -1; # activar todo el sistema de trazado
  11.  
  12. my $cmd = 'show version';
  13. my $host = '10.11.112.3';
  14. my $mensajeerror="";
  15. my $salida;
  16.  
  17. @conn1 = conectar_ssh($host);
  18.  
  19. if (($conn1[0])) {
  20.         $mensajeerror="Equipo=name, IP=$host, Descripcion=$conn1[0]\n<br>";
  21.         print "$mensajeerror\n";
  22. }else
  23. {
  24.         #@out=$conn1[1]->capture("enable\n");
  25.         #@out=$conn1[1]->capture("show running-config");
  26.         #@out=$conn1[1]->system("copy running-config tftp\n");
  27.         #@out=$conn1[1]->capture_tunnel({stdin_data =>"200.58.9.10\n"},"$host",22);
  28.         ### Los anteriores comentarios fueron mis intentos fallidos para lograrlo jejeje ###
  29.         @out=$conn1[1]->capture({stdin_data =>"copy running-config tftp\n 10.11.25.135\nnombre_de_mifichero_de_confg\nquit\n"});
  30.        
  31.         foreach $line1 (@out) {
  32.                 $salida .= "$line1\n";
  33.     }
  34.         print "----- $host -----\noutput:\n$salida]\nerror:\n$mensajeerror\n";
  35. }
  36.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

Solo que en el citado anteriormente me funcionaba para cuando quería realizar un solo comando en todo el script, en el anterior lo ejecuté y me genera el mismo error pero además no me ejecuta lo que requiero.
Saludos,

Jero2528
Avatar de Usuario
jero2528
Perlero nuevo
Perlero nuevo
 
Mensajes: 50
Registrado: 2014-05-14 15:43 @697
Ubicación: Bogota, Colombia

Anterior

Volver a Administración

¿Quién está conectado?

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