EJECUTAR COMANDOS LINUX DESDE PHP

AdjuntoTamaño
Plain text icon sudoers.txt684 bytes
Plain text icon php_ini.txt45.27 KB
Plain text icon httpd.conf_.txt34.07 KB

Forums: 

SALUDOS cORDIALES A TODOS

Estoy tratando y trando y no puedo ejecutar un comando linux desde php para lo cual he modificado el archivo /etc/sudoers para darle permisos al apache.

Adjunto acontinuación mis archivos
/etc/sudoers
php.ini
httpd.conf

LA FUNCION PHP DESDE AL QUE QUIERO EJECUTAR EL COMANDO du es el siguiente:

function Get_Tamanio_Path($path_carpeta)
{
//echo $path_carpeta ---->aqui imprimo haber que me llega y me llega /etc/gonzalo (sin espacios al principio ni al final)

$com = "du -sh $path_carpeta";
$pasa= exec("$com"); // aqui ya probe tambien $pasa= exec($com); sin comillas
$cant=strlen($pasa);
// echo $cant-----//aqui el valor que imprime tambien es cero a pesar que ejecutando du -sh /etc/gonzalo desde la consola de linux me devuelve un valor mayor que cero
return $cant;

}// fin Get_Tamanio_Path($username)

$tam=Get_Tamanio_Path("/etc/gonzalo");

echo "El tamaño de la carpeta es:",$tam;/// el valor que me devuelve es 0;

//EL SOFTWARE QUE UTLIZO Y LAS VERSIONES SON ALS SIGUIENTES:

Linux Centos 4.4

Php 5.1.6

Mysql 5.0.27

Apache 2.0.52

POR FAVOR ESPERO PUEDAN AYUDARME PRONTO,AGRADECERE LOS APORTES DE TODOS , PERO ESPECIALMENTE DE LOS QUE ANTERIORMENTE HAYAN REALIZADO ESTA TAREA , MUCHAS GRACIAS.

Att.

BuscaSolus

comandos linux desde php

revisa esto de pronto te puede ayudar. (sudo)
Yo utilizo fedora:


# sudoers file.
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the sudoers man page for the details on how to write a sudoers file.
#

# Host alias specification

# User alias specification
User_Alias LUDABEGO = daemon

# Cmnd alias specification
Cmnd_Alias MKDIR = /bin/mkdir
Cmnd_Alias CP = /bin/cp
# Defaults specification
Defaults syslog=auth
Defaults:LUDABEGO !lecture
# User privilege specification
root ALL=(ALL) ALL
%wheel ALL = (ALL) ALL

# Uncomment to allow people in group wheel to run all commands
# %wheel ALL=(ALL) ALL

# Same thing without a password
# %wheel ALL=(ALL) NOPASSWD: ALL

# Samples
# %users ALL=/sbin/mount /cdrom,/sbin/umount /cdrom
# %users localhost=/sbin/shutdown -h now
LUDABEGO ALL = NOPASSWD: MKDIR,CP

esto me permite crear carpetas y copiar archivos mediante codigo php, suerte ;)

Ya recuerdo haber leído

Imagen de antares

Ya recuerdo haber leído este post..... mmmmm.... de lo que recuerdo las sugerencias eran (la más obvia) que uses sudo (no lo estás usando, por más que lo configures bien si no lo usas no te servirá, revisa la variable $com en tu código php) y en la configuración de sudoers poner el path completo a du.

Por favor NO DUPLICAR LOS POSTS

Saludos,

antares

gracias ya probe con la opcion que recomiendas.....

GRACIAS ANTERIORMENTE YA PROBE CON AL OPCION QUE ME RECOMIENDAS EN EL ARCHIVO sudoers pero no funciono.

# sudoers file.## This file MUST be edited with the 'visudo' command as root.
## See the sudoers man page for the details on how to write a sudoers file.
## Host alias specification
# User alias specification
User_Alias usuario = daemon
# Cmnd alias specification
Cmnd_Alias MKDIR = /bin/mkdir
Cmnd_Alias CP = /bin/cp
# Defaults specification
Defaults syslog=auth
Defaults:usuario !lecture
# User privilege specificationroot ALL=(ALL) ALL
%wheel ALL = (ALL) ALL
# Uncomment to allow people in group wheel to run all commands
# %wheel ALL=(ALL) ALL
# Same thing without a password
# %wheel ALL=(ALL) NOPASSWD: ALL
# Samples# %users ALL=/sbin/mount /cdrom,/sbin/umount /cdrom
# %users localhost=/sbin/shutdown -h now
usuario ALL = NOPASSWD: MKDIR,CP

Lo que pasa es que no estas

Imagen de Monkito

Lo que pasa es que no estas usando el comando "sudo", lo que tienes como

$com = "du -sh $path_carpeta";

debería quedar como

$com = "sudo du -sh $path_carpeta";

bye

Cogito Ergo Sum

------------
counter.li.org

Cogito Ergo Sum

gracias de todas formas.....

ya probe con otras variates de la functio php , te la pongo acontinuacion:

LA FUNCION PHP DESDE AL QUE QUIERO EJECUTAR EL COMANDO du es el siguiente:

function Get_Tamanio_Path($path_carpeta)
{
//echo $path_carpeta ---->aqui imprimo haber que me llega y me llega /etc/gonzalo (sin espacios al principio ni al final)

$com = "sudo du -sh $path_carpeta"; // ademas probe con sudo -u apache du -sh $path_carpeta y con otros usuarios no apache ...osea sudo -u usuario -p el_password du -sh $path_carpeta (claor q para esta ultima variante en el sudoers debo pedirle password)

$pasa= exec("$com"); // aqui ya probe tambien $pasa= exec($com); sin comillas
$cant=strlen($pasa);
// echo $cant-----//aqui el valor que imprime tambien es cero a pesar que ejecutando du -sh /etc/gonzalo desde la consola de linux me devuelve un valor mayor que cero
return $cant;

}// fin Get_Tamanio_Path($username)

$tam=Get_Tamanio_Path("/etc/gonzalo");

echo "El tamaño de la carpeta es:",$tam;/// el valor que me devuelve es 0;

PD. LO SIENTO POR NO ESPECIFICAR LAS VARIANTES QUE PROBE ANTERIORMENTE.

Problema similar

Imagen de omegajack

Hola soy nuevo tanto en linux como en el foro, quizas ni leas este mensaje pero espero que si para que me puedas ayudar si te es posible, tengo un problema similar al que pasaste, tengo un script en php que deseo ejecute instrucciones de asterisk, las lineas mas importantes son las siguientes:

El script en php
exec("/usr/sbin/asterisk -rx 'sip show peers'" , $result);
foreach ($result as $line)
echo "$line\n";

En etc/sudoers
## Sudoers allows particular users to run various commands as
## the root user, without needing the root password.
##
## Examples are provided at the bottom of the file for collections
## of related commands, which can then be delegated out to particular
## users or groups.
##
## This file must be edited with the 'visudo' command.

## Host Aliases
## Groups of machines. You may prefer to use hostnames (perhap using
## wildcards for entire domains) or IP addresses instead.
# Host_Alias FILESERVERS = fs1, fs2
# Host_Alias MAILSERVERS = smtp, smtp2

## User Aliases
## These aren't often necessary, as you can use regular groups
## (ie, from files, LDAP, NIS, etc) in this file - just use %groupname
## rather than USERALIAS
## User_Alias ADMINS = jsmith, mikem

## Command Aliases

## These are groups of related commands...

##Apache
Cmnd_Alias ASTERISK=/usr/sbin/asterisk

## Networking
Cmnd_Alias NETWORKING = /sbin/route, /sbin/ifconfig, /bin/ping, /sbin/dhclient, /usr/bin/net, /sbin/iptables, /usr/bin/rfcomm, /usr/bin/wvdial, /sbin/iwconf$

## Installation and management of software
Cmnd_Alias SOFTWARE = /bin/rpm, /usr/bin/up2date, /usr/bin/yum

## Services
Cmnd_Alias SERVICES = /sbin/service, /sbin/chkconfig

## Updating the locate database
Cmnd_Alias LOCATE = /usr/sbin/updatedb

## Storage
Cmnd_Alias STORAGE = /sbin/fdisk, /sbin/sfdisk, /sbin/parted, /sbin/partprobe, /bin/mount, /bin/umount

## Delegating permissions
Cmnd_Alias DELEGATING = /usr/sbin/visudo, /bin/chown, /bin/chmod, /bin/chgrp

## Processes
Cmnd_Alias PROCESSES = /bin/nice, /bin/kill, /usr/bin/kill, /usr/bin/killall

## Drivers
Cmnd_Alias DRIVERS = /sbin/modprobe

# Defaults specification

#
# Disable "ssh hostname sudo ", because it will show the password in clear.
# You have to run "ssh -t hostname sudo ".
#
#Defaults requiretty

Defaults env_reset
Defaults env_keep = "COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR \
LS_COLORS MAIL PS1 PS2 QTDIR USERNAME \
LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION \
LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC \
LC_PAPER LC_TELEPHONE LC_TIME LC_ALL LANGUAGE LINGUAS \
_XKB_CHARSET XAUTHORITY"

## Next comes the main part: which users can run what software on
## which machines (the sudoers file can be shared between multiple
## systems).
## Syntax:
##
## user MACHINE=COMMANDS
##
## The COMMANDS section may have other options added to it.
##
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
%apache ALL=(ALL) ALL

## Allows members of the 'sys' group to run networking, software,
## service management apps and more.
# %sys ALL = NETWORKING, SOFTWARE, SERVICES, STORAGE, DELEGATING, PROCESSES, LOCATE, DRIVERS

## Allows people in group wheel to run all commands
# %wheel ALL=(ALL) ALL

## Same thing without a password
# %wheel ALL=(ALL) NOPASSWD: ALL

## Allows members of the users group to mount and unmount the
## cdrom as root
# %users ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom

## Allows members of the users group to shutdown this system
# %users localhost=/sbin/shutdown -h now

Segun yo y lo que he entendido del tema defino un alias para el comando asterisk con
##Apache
Cmnd_Alias ASTERISK=/usr/sbin/asterisk

Y le doy los permisos con
%apache ALL=(ALL) ALL

Pero cuando doy el comando sudo -l solo me muestra esto(solo el usuario root)
User root may run the following commands on this host:
(ALL) ALL

Y mi script sigue sin funcionar, podrias ayudarme porfavor?

Cita: %apache ALL=(ALL)

Imagen de deathUser

[quote]%apache ALL=(ALL) ALL[/quote]

Si no me equivoco eso hará que los "usuarios del grupo apache" puedan ejecutar todos los comandos, pero te va a pedir el password del usuario, deberías colocar NOPASSWD (revisa el manual para la sintaxis correcta) en el sudoers para que corran de manera no interactiva como lo requieres para poder llamarlos desde el PHP

Suerte ...

bye
:)

Ya lo hice y sigue sin funcionar

Imagen de omegajack

De antemano muchisimas gracias por tomarte la molestia de responder mi pregunta, a lo que desde ahora como parte de la comunidad de ecualog me pongo a tu disposicion para lo que te pueda ayudar, como referencia lo que manejo actualmente en mi trabajo es asterisk por lo que si necesitas y tengo el conocimiento sobre como solucionar algun problema en el mismo basta con que te pongas en contacto conmigo que si puedo con gusto te ayudare.

volviendo al tema, he agregado la parte que hace que no pida el password
%apache ALL=(ALL) ALL NOPASSWD: ALL

Estoy usando el scrip llamando al usuario apache de la siguiente manera
<?
exec("sudo -u apache /usr/sbin/asterisk -rx 'sip show peers'" , $result);
foreach ($result as $line)
echo "$line\n";
?>

Sin embargo sigue sin funcionar, simplemente el script no muestra nada, por otro lado en los logs me muestra
tail -f /etc/httpd/logs/error_log
[Thu Aug 28 08:07:22 2008] [notice] caught SIGTERM, shutting down
[Thu Aug 28 08:08:03 2008] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Thu Aug 28 08:08:43 2008] [notice] Digest: generating secret for digest authentication ...
[Thu Aug 28 08:08:43 2008] [notice] Digest: done
[Thu Aug 28 08:08:43 2008] [notice] mod_python: Creating 4 session mutexes based on 256 max processes and 0 max threads.
>>> sudoers file: syntax error, line 77 <<<
sudo: parse error in /etc/sudoers near line 77
[Thu Aug 28 08:08:43 2008] [notice] Apache/2.2.3 (CentOS) configured -- resuming normal operations

ese error de sintaxis supongo es por la linea que agregue, pero segun lo que leo y en el mismo archivo de sudoers... esa es la sintaxis
%apache ALL=(ALL) ALL NOPASSWD: ALL

Que estoy haciendo mal?

Páginas