• Publicidad

Net::OpenSSH Problema ejecutando script desde Apache

¿Ya sabes lo que es una referencia? Has progresado, el nível básico es cosa del pasado y ahora estás listo para el siguiente nivel.

Net::OpenSSH Problema ejecutando script desde Apache

Notapor jero2528 » 2017-03-10 09:31 @438

Saludos, estimados.


Actualmente he desarrollado un script de automatización que se encarga de recibir un archivo de texto para lectura y luego debe conectarse a un equipo Fortinet por SSH, estando en mi servidor (redhat) sobre la ruta:
Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
  1. /usr/local/scripts/apply_healthy_internet.pl 2 URLFILTER2###inet_sano_parsed_20170309.txt
Coloreado en 0.003 segundos, usando GeSHi 1.0.8.4

Ejecuto ese script y hace el trabajo sin inconvenientes, todo es una maravilla :) El problema se presenta cuando se ejecuta desde la página web que está alojada en el mismo servidor, como lo ilustro a continuación:
hi.png
ejecutado desde la web
hi.png (9.74 KiB) Visto 2924 veces

Esta página ejecuta un comando desde PHP:
Sintáxis: [ Descargar ] [ Ocultar ]
Using php Syntax Highlighting
  1. $filetemp = "/usr/local/scripts/logs/apply_healthy_internet.log";
  2. $command = "perl ./apply_healthy_internet.pl $numberList \"" .$nameList. "###" . $filename . "\" > $filetemp
  3. //$command = "cd /usr/local/scripts/ && perl ./apply_healthy_internet.pl $numberList \"" .$nameList. "###" . $filename . "\" > $filetemp 2>&1";
  4. system($command);
Coloreado en 0.020 segundos, usando GeSHi 1.0.8.4

Como lo indiqué antes, tomando el comando que me retorna la web, y ejecutándolo desde la consola del servidor, el script funciona, pero validando el log que es generado por la ejecución vía web obtengo esta respuesta:
Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
  1. [root@server mysite]# cat /usr/local/scripts/logs/apply_healthy_internet.log
  2. total: 40300
  3.  
  4. imposible conectar con servidor remoto 190.2.23.13: unable to establish master SSH connection: the authenticity of the target host can't be established, the remote host public key is probably not present on the '~/.ssh/known_hosts' file at ./apply_healthy_internet.pl line 131, <$fh> line 4000.
  5. done
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

He logrado cambiar el script para que me retornara ese error y esta es la función donde se encuentra la línea en cuestión:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. sub conectar_openssh{
  2.         ## ---------------------------------------------------------------
  3.         ## Inicializacion de variables
  4.         ## ---------------------------------------------------------------
  5.         my $ip   = $_[0];
  6.         my ($stderr) = ('');
  7.         #Aqui es donde se presenta el error en mi script
  8.         $ssh = Net::OpenSSH->new($ip, user => $userdefault, passwd => $passdefault, port => 22, master_opts => [-o => "UserKnownHostsFile=~/.ssh/known_hosts"]);
  9.         if ($ssh->error) {
  10.                 $stderr= $ssh->error;
  11.                 warn "imposible conectar con servidor remoto $ip: ". $ssh->error;
  12.                 return $stderr, $ssh;
  13.         }
  14.         $stderr=$ssh->error;
  15.         return $stderr, $ssh;  
  16. }
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4

Sin embargo, el problema inicial era que no encontraba el directorio
Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
  1. /var/www/.libnet-openssh-perl/
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
entonces decidí crearlo con un mkdir() al igual que el /.ssh/known_hosts (este archivo sí contiene la public key del servidor) sobre esa ruta, pero el problema persiste :cry: :cry:

Espero que me puedan ayudar. He estado mirando en la web y a muchos les sucede lo mismo pero no han recibido una respuesta a este problema. :( :( Muchas gracias de antemano.
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: Net::OpenSSH Problema ejecutando script desde Apache

Notapor explorer » 2017-03-10 14:02 @626

Creo que el problema está en el uso de '~'.

Cuando lo ejecutas como usuario, ese '~' es el $HOME de tu usuario, donde se localiza el subdirectorio .ssh/

Pero cuando lo ejecutas desde el Apache, ese Apache es otro usuario (generalmente, www-data, www, httpd, nobody, etc.) Y claro, '~' estará en otro directorio.

Mi consejo es que uses rutas absolutas siempre.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Net::OpenSSH Problema ejecutando script desde Apache

Notapor jero2528 » 2017-03-10 15:39 @693

Gracias explorer,

si eso también lo he probado, incluso he puesto el del usuario root y tampoco me ha funcionado :(.
así queda la linea de conexion en el script:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. $ssh = Net::OpenSSH->new($ip, user => $userdefault, passwd => $passdefault, port => 22, master_opts => [-o => "UserKnownHostsFile=/var/www/.ssh/known_hosts"]);
  2.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


lo que me da la salida:
hi2.png
hi2.png (20.74 KiB) Visto 2879 veces
Saludos,

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

Re: Net::OpenSSH Problema ejecutando script desde Apache

Notapor explorer » 2017-03-11 09:07 @422

Pues en el mensaje de error te dice que no te está haciendo caso con respecto a la localización del archivo known_hosts. Sigue diciendo que no puede acceder a '~/.ssh/known_hosts' (que es el valor por defecto de UserKnownHostsFile si no se le dice nada a openssh).

Prueba con este cambio (quitarle el carácter '='):
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. $ssh = Net::OpenSSH->new($ip,
  2.         user        => $userdefault,
  3.         passwd      => $passdefault,
  4.         port        => 22,
  5.         master_opts => [
  6.                 -o  => "UserKnownHostsFile /var/www/.ssh/known_hosts",
  7.         ],
  8. );
Coloreado en 0.001 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: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Net::OpenSSH Problema ejecutando script desde Apache

Notapor jero2528 » 2017-03-13 10:42 @487

Gracias, explorer.

Ya realicé la prueba con el cambio que me indicaste pero sigue sin funcionar :(

Aparece el mismo error.
Saludos,

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

Re: Net::OpenSSH Problema ejecutando script desde Apache

Notapor explorer » 2017-03-13 17:21 @764

He hecho una prueba desde la línea de comandos, añadiendo la opción -v, y efectivamente, hay que poner el carácter '=', y sin espacios.

ssh -v -o UserKnownHostsFile=/var/www/.ssh/known_hosts [email protected]

Prueba a ver si con la opción -v te da algo más de información. Puedes poner hasta 3 '-v' para aumentar la verbosidad del comando.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Net::OpenSSH Problema ejecutando script desde Apache

Notapor jero2528 » 2017-03-14 08:26 @393

Hola de nuevo, explorer.

Sí, realicé la prueba que me indicas y usando 3 '-v':
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. $ssh = Net::OpenSSH->new($ip, user => $userdefault, passwd => $passdefault, port => 22, master_opts => '-vvv');
  2.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


Obtengo este resultado:
Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
  1. OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013
  2. debug1: Reading configuration data /etc/ssh/ssh_config
  3. debug1: Applying options for *
  4. debug2: ssh_connect: needpriv 0
  5. debug1: Connecting to 190.60.0.12 [190.60.0.12] port 22.
  6. debug1: Connection established.
  7. debug1: identity file /var/www/.ssh/id_rsa type -1
  8. debug1: identity file /var/www/.ssh/id_rsa-cert type -1
  9. debug1: identity file /var/www/.ssh/id_dsa type -1
  10. debug1: identity file /var/www/.ssh/id_dsa-cert type -1
  11. debug1: identity file /var/www/.ssh/id_ecdsa type -1
  12. debug1: identity file /var/www/.ssh/id_ecdsa-cert type -1
  13. debug1: Remote protocol version 2.0, remote software version SNcyS_S
  14. debug1: no match: SNcyS_S
  15. debug1: Enabling compatibility mode for protocol 2.0
  16. debug1: Local version string SSH-2.0-OpenSSH_5.3
  17. debug2: fd 3 setting O_NONBLOCK
  18. debug1: SSH2_MSG_KEXINIT sent
  19. debug3: Wrote 960 bytes for a total of 981
  20. debug1: SSH2_MSG_KEXINIT received
  21. debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
  22. debug2: kex_parse_kexinit: ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,ssh-rsa,ssh-dss
  23. debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
  24. debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
  25. debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
  26. debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
  27. debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
  28. debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
  29. debug2: kex_parse_kexinit:
  30. debug2: kex_parse_kexinit:
  31. debug2: kex_parse_kexinit: first_kex_follows 0
  32. debug2: kex_parse_kexinit: reserved 0
  33. debug2: kex_parse_kexinit: curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1
  34. debug2: kex_parse_kexinit: ssh-rsa,ssh-ed25519
  35. debug2: kex_parse_kexinit: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128
  36. debug2: kex_parse_kexinit: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128
  37. debug2: kex_parse_kexinit: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1,hmac-ripemd160-etm@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com
  38. debug2: kex_parse_kexinit: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1,hmac-ripemd160-etm@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com
  39. debug2: kex_parse_kexinit: none,zlib@openssh.com
  40. debug2: kex_parse_kexinit: none,zlib@openssh.com
  41. debug2: kex_parse_kexinit:
  42. debug2: kex_parse_kexinit:
  43. debug2: kex_parse_kexinit: first_kex_follows 0
  44. debug2: kex_parse_kexinit: reserved 0
  45. debug2: mac_setup: found hmac-sha1
  46. debug1: kex: server->client aes128-ctr hmac-sha1 none
  47. debug2: mac_setup: found hmac-sha1
  48. debug1: kex: client->server aes128-ctr hmac-sha1 none
  49. debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<2048<8192) sent
  50. debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
  51. debug3: Wrote 24 bytes for a total of 1005
  52. debug2: dh_gen_key: priv key bits set: 157/320
  53. debug2: bits set: 1002/2048
  54. debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
  55. debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
  56. debug3: Wrote 272 bytes for a total of 1277
  57. debug3: check_host_in_hostfile: host 190.60.0.12 filename /var/www/.ssh/known_hosts
  58. debug3: check_host_in_hostfile: host 190.60.0.12 filename /var/www/.ssh/known_hosts
  59. debug3: check_host_in_hostfile: host 190.60.0.12 filename /etc/ssh/ssh_known_hosts
  60. debug3: check_host_in_hostfile: host 190.60.0.12 filename /etc/ssh/ssh_known_hosts
  61. debug3: check_host_in_hostfile: host 190.60.0.12 filename /var/www/.ssh/known_hosts
  62. debug3: check_host_in_hostfile: host 190.60.0.12 filename /etc/ssh/ssh_known_hosts
  63. debug2: no key of type 0 for host 190.60.0.12
  64. debug3: check_host_in_hostfile: host 190.60.0.12 filename /var/www/.ssh/known_hosts2
  65. debug3: check_host_in_hostfile: host 190.60.0.12 filename /etc/ssh/ssh_known_hosts2
  66. debug3: check_host_in_hostfile: host 190.60.0.12 filename /var/www/.ssh/known_hosts
  67. debug3: check_host_in_hostfile: host 190.60.0.12 filename /etc/ssh/ssh_known_hosts
  68. debug2: no key of type 2 for host 190.60.0.12
  69. debug3: check_host_in_hostfile: host 190.60.0.12 filename /var/www/.ssh/known_hosts2
  70. debug3: check_host_in_hostfile: host 190.60.0.12 filename /etc/ssh/ssh_known_hosts2
  71. debug3: check_host_in_hostfile: host 190.60.0.12 filename /var/www/.ssh/known_hosts
  72. debug3: check_host_in_hostfile: host 190.60.0.12 filename /etc/ssh/ssh_known_hosts
  73. debug2: no key of type 3 for host 190.60.0.12
  74. imposible conectar con servidor remoto 190.60.0.12: unable to establish master SSH connection: the authenticity of the target host can't be established, the remote host public key is probably not present on the '~/.ssh/known_hosts' file at ./apply_healthy_internet.pl line 131, <$fh> line 4000.
  75. done
  76.  
Coloreado en 0.003 segundos, usando GeSHi 1.0.8.4


Pero no logro entender bien lo que me indica el log.
Saludos,

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

Re: Net::OpenSSH Problema ejecutando script desde Apache

Notapor explorer » 2017-03-14 16:37 @734

Si quitas la opción '-o', no avanzamos nada. Prueba con

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
        master_opts => [
                -o  => "UserKnownHostsFile=/var/www/.ssh/known_hosts",
                -v  => "-v -v",
        ],
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


P.D.: Mirando de nuevo el log, sí que veo que accede a /var/www/.ssh/known_hosts, e intenta sacar la clave correspondiente al servidor 190.60.0.12, pero dice que no lo encuentra.

¿Has comprobado que desde la línea de comandos, el comando ssh funciona con ese host? Dices en tu primer mensaje que sí, entonces yo deduzco que tiene que ser un problema de permisos, que no le permiten leer /var/www/.ssh/known_hosts.

¿Has mirado en los logs de actividad del servidor web?
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Net::OpenSSH Problema ejecutando script desde Apache

Notapor jero2528 » 2017-03-15 16:15 @718

Hola, explorer.

Muchas gracias por tu ayuda :D Se pudo resolver ajustando ciertos permisos en los archivos del directorio /var/www/:
permisosOpenSSH.png
comando ls -ltra /var/www/ en RedHat
permisosOpenSSH.png (3.98 KiB) Visto 2802 veces

La configuración en la conexión quedó así:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. $ssh = Net::OpenSSH->new($ip,
  2.         user        => $userdefault,
  3.         passwd      => $passdefault,
  4.         port        => 22,
  5.         ctl_dir     => "/var/www/.libnet-openssh-perl",
  6.         master_opts => [
  7.                 -o  => "UserKnownHostsFile=/var/www/.ssh/known_hosts",
  8.         ],
  9. );
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

Espero esto le ayude a otros que tengan el mismo inconveniente :D :D :D :mrgreen:
Saludos,

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


Volver a Intermedio

¿Quién está conectado?

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