elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Sigue las noticias más importantes de seguridad informática en el Twitter! de elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Desarrollo Web
| | |-+  PHP (Moderador: #!drvy)
| | | |-+  Insertar script python en pagina php
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Insertar script python en pagina php  (Leído 5,022 veces)
melanoma69

Desconectado Desconectado

Mensajes: 4


Ver Perfil
Insertar script python en pagina php
« en: 1 Agosto 2014, 05:24 am »

Buenas noches amigos, llevo tiempo utilizando esta pagina para resolver mis dudas sobre php, creación de webs, etc la verdad es que es utilisima!!

Me ha surgido una duda hoy mientras trataba de ejecutar un comando python en mi web de seguridad casera. El tema es el siguiente, tengo un script pi_garage_alert.py que chequea cambios en mis puertos gpio y cuando hay un cambio lanza intentofoto.py. Intentofoto.py hace 4 fotos, envía un mail, sube las fotos a dropbox y borra una carpeta.

Cuando ejecuto en mi web boton.php (si lo asocio a pi_garage_alert.py no hace nada) si lo asocio a intentofoto.py lo único que hace es que enviar el mail, sin hacer caso a las demás ordenes. Aquí os dejo el código, tanto para que lo utiliceis como por si algún alma caritativa me puede ayudar.

El objetivo final de esto es crear un botón que active y desactive mi alarma (intentofoto.py)

intentofoto.py

Código
  1. #!/usr/bin/env python
  2.  
  3. import time
  4. import os
  5. import sys
  6. import re
  7. import subprocess
  8. import datetime
  9. import smtplib
  10. from email.MIMEMultipart import MIMEMultipart
  11. from email.MIMEBase import MIMEBase
  12. from email.MIMEText import MIMEText
  13. from email.Utils import COMMASPACE, formatdate
  14. from email import Encoders
  15.  
  16. ###### CAPTURA DE IMAGENES############
  17.  
  18. SnapImage = "/var/www/fotospuerta/" + datetime.datetime.now().strftime("%d-%m-%Y_%H:%M:%S:%f") + ".jpg"
  19. subprocess.call(["/usr/bin/wget","-O",SnapImage,"http://melanoma.no-ip.biz:9000/?action=snapshot"])
  20.  
  21. SnapImage = "/var/www/fotospuerta/" + datetime.datetime.now().strftime("%d-%m-%Y_%H:%M:%S:%f") + ".jpg"
  22. subprocess.call(["/usr/bin/wget","-O",SnapImage,"http://melanoma.no-ip.biz:9000/?action=snapshot"])
  23.  
  24. SnapImage = "/var/www/fotospuerta/" + datetime.datetime.now().strftime("%d-%m-%Y_%H:%M:%S:%f") + ".jpg"
  25. subprocess.call(["/usr/bin/wget","-O",SnapImage,"http://melanoma.no-ip.biz:9000/?action=snapshot"])
  26.  
  27. SnapImage = "/var/www/fotospuerta/" + datetime.datetime.now().strftime("%d-%m-%Y_%H:%M:%S:%f") + ".jpg"
  28. subprocess.call(["/usr/bin/wget","-O",SnapImage,"http://melanoma.no-ip.biz:9000/?action=snapshot"])
  29.  
  30. #######ENVIO DE EMAILS#########
  31.  
  32. def sendMail(to, fro, subject, text, files=[],server="localhost"):
  33.    assert type(to)==list
  34.    assert type(files)==list
  35.  
  36.  
  37.    msg = MIMEMultipart()
  38.    msg['From'] = fro
  39.    msg['To'] = COMMASPACE.join(to)
  40.    msg['Date'] = formatdate(localtime=True)
  41.    msg['Subject'] = subject
  42.  
  43.    msg.attach( MIMEText(text) )
  44.  
  45.    for file in files:
  46.        part = MIMEBase('application', "octet-stream")
  47.        part.set_payload( open(file,"rb").read() )
  48.        Encoders.encode_base64(part)
  49.        part.add_header('Content-Disposition', 'attachment; filename="%s"'
  50.                       % os.path.basename(file))
  51.        msg.attach(part)
  52.  
  53.    smtp = smtplib.SMTP(server)
  54.    smtp.sendmail(fro, to, msg.as_string() )
  55.    smtp.close()
  56.  
  57. sendMail(['<laplazaproducciones@gmail.com>'],'phpGeek <laplazaproducciones@gmail.com>','Alerta','La puerta de la calle ha sido abierta')
  58.  
  59. ####### SUBIDA DE IMAGENES#############
  60.  
  61. os.system("/home/pi/Dropbox-Uploader/dropbox_uploader.sh -s upload /var/www/fotospuerta/ /")
  62. os.system("rm -f /var/www/fotospuerta/*")
  63.  
  64. #time.sleep(1)


pi_garage_alert.py

Código
  1. #!/usr/bin/python2.7
  2.  
  3. import RPi.GPIO as GPIO
  4. import time
  5. import subprocess
  6. import re
  7. import sys
  8. import logging
  9. import smtplib
  10. import os
  11. import httplib2
  12. from sleekxmpp.xmlstream import resolver, cert
  13. import ssl
  14. import traceback
  15.  
  16. from time import strftime
  17. from datetime import timedelta
  18.  
  19. sys.path.append('/usr/local/etc')
  20. import pi_garage_alert_config as cfg
  21.  
  22. ##############################################################################
  23. # Sensor support
  24. ##############################################################################
  25.  
  26. def get_garage_door_state(pin):
  27.    """Returns the state of the garage door on the specified pin as a string
  28.  
  29.    Args:
  30.        pin: GPIO pin number.
  31.    """
  32.    if GPIO.input(pin):
  33.        state = 'open'
  34.    else:
  35.        state = 'closed'
  36.  
  37.    return state
  38.  
  39. def get_uptime():
  40.    """Returns the uptime of the RPi as a string
  41.    """
  42.    with open('/proc/uptime', 'r') as uptime_file:
  43.        uptime_seconds = int(float(uptime_file.readline().split()[0]))
  44.        uptime_string = str(timedelta(seconds=uptime_seconds))
  45.    return uptime_string
  46.  
  47. def get_gpu_temp():
  48.    """Return the GPU temperature as a Celsius float
  49.    """
  50.    cmd = ['vcgencmd', 'measure_temp']
  51.  
  52.    measure_temp_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  53.    output = measure_temp_proc.communicate()[0]
  54.  
  55.    gpu_temp = 'unknown'
  56.    gpu_search = re.search('([0-9.]+)', output)
  57.  
  58.    if gpu_search:
  59.        gpu_temp = gpu_search.group(1)
  60.  
  61.    return float(gpu_temp)
  62.  
  63. def get_cpu_temp():
  64.    """Return the CPU temperature as a Celsius float
  65.    """
  66.    cpu_temp = 'unknown'
  67.    with open("/sys/class/thermal/thermal_zone0/temp", "r") as temp_file:
  68.        cpu_temp = float(temp_file.read()) / 1000.0
  69.  
  70.    return cpu_temp
  71.  
  72. def rpi_status():
  73.    """Return string summarizing RPi status
  74.    """
  75.    return "Temperatura CPU: %.1f, Temperatura GPU: %.1f, Tiempo Encendido Pi: %s" % (get_gpu_temp(), get_cpu_temp(), get_uptime())
  76.  
  77. ##############################################################################
  78. # Logging and alerts
  79. ##############################################################################
  80.  
  81. def send_alerts(logger, alert_senders, recipients, subject, msg):
  82.    """Send subject and msg to specified recipients
  83.  
  84.    Args:
  85.        recipients: An array of strings of the form type:address
  86.        subject: Subject of the alert
  87.        msg: Body of the alert
  88.    """
  89.    for recipient in recipients:
  90.        if recipient[:6] == 'email:':
  91.            alert_senders['Email'].send_email(recipient[6:], subject, msg)
  92.        else:
  93.            logger.error("Unrecognized recipient type: %s", recipient)
  94.  
  95. ##############################################################################
  96. # Misc support
  97. ##############################################################################
  98.  
  99. def truncate(input_str, length):
  100.    """Truncate string to specified length
  101.  
  102.    Args:
  103.        input_str: String to truncate
  104.        length: Maximum length of output string
  105.    """
  106.    if len(input_str) < (length - 3):
  107.        return input_str
  108.  
  109.    return input_str[:(length - 3)] + '...'
  110.  
  111. def format_duration(duration_sec):
  112.    """Format a duration into a human friendly string"""
  113.    days, remainder = divmod(duration_sec, 86400)
  114.    hours, remainder = divmod(remainder, 3600)
  115.    minutes, seconds = divmod(remainder, 60)
  116.  
  117.    ret = ''
  118.    if days > 1:
  119.        ret += "%d days " % (days)
  120.    elif days == 1:
  121.        ret += "%d day " % (days)
  122.  
  123.    if hours > 1:
  124.        ret += "%d hours " % (hours)
  125.    elif hours == 1:
  126.        ret += "%d hour " % (hours)
  127.  
  128.    if minutes > 1:
  129.        ret += "%d minutes" % (minutes)
  130.    if minutes == 1:
  131.        ret += "%d minute" % (minutes)
  132.  
  133.    if ret == '':
  134.        ret += "%d seconds" % (seconds)
  135.  
  136.    return ret
  137.  
  138.  
  139. ##############################################################################
  140. # Main functionality
  141. ##############################################################################
  142. class PiGarageAlert(object):
  143.    """Class with main function of Pi Garage Alert"""
  144.  
  145.    def __init__(self):
  146.        self.logger = logging.getLogger(__name__)
  147.  
  148.    def main(self):
  149.        """Main functionality
  150.        """
  151.  
  152.        try:
  153.            # Set up logging
  154.            log_fmt = '%(asctime)-15s %(levelname)-8s %(message)s'
  155.            log_level = logging.INFO
  156.  
  157.            if sys.stdout.isatty():
  158.                # Connected to a real terminal - log to stdout
  159.                logging.basicConfig(format=log_fmt, level=log_level)
  160.            else:
  161.                # Background mode - log to file
  162.                logging.basicConfig(format=log_fmt, level=log_level, filename=cfg.LOG_FILENAME)
  163.  
  164.            # Banner
  165.            self.logger.info("==========================================================")
  166.            self.logger.info("Encendiendo Alarma de la Puerta de Entrada")
  167.  
  168.            # Use Raspberry Pi board pin numbers
  169.            self.logger.info("Configurando Ajustes Globales")
  170.            GPIO.setmode(GPIO.BOARD)
  171.  
  172.            # Configure the sensor pins as inputs with pull up resistors
  173.            for door in cfg.GARAGE_DOORS:
  174.                self.logger.info("Configurando pin %d para \"%s\"", door['pin'], door['name'])
  175.                GPIO.setup(door['pin'], GPIO.IN, pull_up_down=GPIO.PUD_UP)
  176.  
  177.            # Last state of each garage door
  178.            door_states = dict()
  179.  
  180.            # time.time() of the last time the garage door changed state
  181.            time_of_last_state_change = dict()
  182.  
  183.            # Index of the next alert to send for each garage door
  184.            alert_states = dict()
  185.  
  186.  
  187.            # Read initial states
  188.            for door in cfg.GARAGE_DOORS:
  189.                name = door['name']
  190.                state = get_garage_door_state(door['pin'])
  191.  
  192.                door_states[name] = state
  193.                time_of_last_state_change[name] = time.time()
  194.                alert_states[name] = 0
  195.  
  196.                self.logger.info("Estado Inicial de \"%s\" es %s", name, state)
  197.  
  198.            status_report_countdown = 5
  199.            while True:
  200.                for door in cfg.GARAGE_DOORS:
  201.                    name = door['name']
  202.                    state = get_garage_door_state(door['pin'])
  203.                    time_in_state = time.time() - time_of_last_state_change[name]
  204.  
  205.                    # Check if the door has changed state
  206.                    if door_states[name] != state:
  207.                        door_states[name] = state
  208.                        time_of_last_state_change[name] = time.time()
  209.                        self.logger.info("Estado de \"%s\" ha cambiado a %s despues de %.0f sec", name, state, time_in_state)
  210.  
  211. #if state == 'open':
  212. os.system("python /home/pi/python/intentofoto.py")
  213. #os.system("/home/pi/Dropbox-Uploader/dropbox_uploader.sh -s upload /var/www/fotospuerta/ /")
  214. #os.system("rm -f /var/www/fotospuerta/*")
  215.  
  216.  
  217.                        # Reset alert when door changes state
  218.                        if alert_states[name] > 0:
  219.                            # Use the recipients of the last alert
  220.                            recipients = door['alerts'][alert_states[name] - 1]['recipients']
  221.                            send_alerts(self.logger, alert_senders, recipients, name, "%s esta ahora %s" % (name, state))
  222.                            alert_states[name] = 0
  223.  
  224.                        # Reset time_in_state
  225.                        time_in_state = 0
  226.  
  227.                    # See if there are more alerts
  228.                    if len(door['alerts']) > alert_states[name]:
  229.                        # Get info about alert
  230.                        alert = door['alerts'][alert_states[name]]
  231.  
  232.                        # Has the time elapsed and is this the state to trigger the alert?
  233.                        if time_in_state > alert['time'] and state == alert['state']:
  234.                            send_alerts(self.logger, alert_senders, alert['recipients'], name, "%s ha sido %s %d seconds!" % (name, state, time_in_state))
  235.                            alert_states[name] += 1
  236.  
  237.                # Periodically log the status for debug and ensuring RPi doesn't get too hot
  238.                status_report_countdown -= 1
  239.                if status_report_countdown <= 0:
  240.                    status_msg = rpi_status()
  241.  
  242.                    for name in door_states:
  243.                        status_msg += ", %s: %s/%d/%d" % (name, door_states[name], alert_states[name], (time.time() - time_of_last_state_change[name]))
  244.  
  245.                    self.logger.info(status_msg)
  246.  
  247.                    status_report_countdown = 600
  248.  
  249.                # Poll every 1 second
  250.                time.sleep(1)
  251.        except KeyboardInterrupt:
  252.            logging.critical("Terminating due to keyboard interrupt")
  253.        except:
  254.            logging.critical("Terminating due to unexpected error: %s", sys.exc_info()[0])
  255.            logging.critical("%s", traceback.format_exc())
  256.  
  257.        GPIO.cleanup()
  258.  
  259. if __name__ == "__main__":
  260.    PiGarageAlert().main()


boton.php

Código
  1. <?php
  2.  
  3. $command = escapeshellcmd('/var/www/pi_garage_alert.py');
  4. $output = shell_exec($command);
  5. echo $output;
  6.  
  7. ?>

MUCHAS GRACIAS DE ANTEMANO Y LO SIENTO SI ES MUY LARGO!! :D


« Última modificación: 1 Agosto 2014, 16:09 pm por #!drvy » En línea

MinusFour
Moderador Global
***
Desconectado Desconectado

Mensajes: 5.529


I'm fourth.


Ver Perfil WWW
Re: Insertar script python en pagina php
« Respuesta #1 en: 1 Agosto 2014, 15:55 pm »

¿Cual es el output al ejecutar pi_garage_alert.py? ¿El usuario del proceso HTTP tiene permisos para ejecutar el proceso?


En línea

melanoma69

Desconectado Desconectado

Mensajes: 4


Ver Perfil
Re: Insertar script python en pagina php
« Respuesta #2 en: 1 Agosto 2014, 16:31 pm »

Muchas gracias por responder amigo. A que te refieres con el output? La verdad es que no se muy bien cual es el usuario del proceso html. Te adjunto el log de errores de apache2 a ver si me puedes echar una manilla.

Código
  1. /var/www/pi_garage_alert.py:257: RuntimeWarning: No channels have been set up yet - nothing to clean up!  Try cleaning up at the end of your program instead!
  2.  GPIO.cleanup()
  3. /var/www/fotospuerta/31-07-2014_22:15:20:311136.jpg: Permission denied
  4. /var/www/fotospuerta/31-07-2014_22:15:20:406414.jpg: Permission denied
  5. /var/www/fotospuerta/31-07-2014_22:36:21:010600.jpg: Permission denied
  6. /var/www/fotospuerta/31-07-2014_22:36:21:710177.jpg: Permission denied
  7. CRITICAL:root:Terminating due to unexpected error: <type 'exceptions.IOError'>
  8. CRITICAL:root:Traceback (most recent call last):
  9.  File "/var/www/pi_garage_alert.py", line 162, in main
  10.    logging.basicConfig(format=log_fmt, level=log_level, filename=cfg.LOG_FILENAME)
  11.  File "/usr/lib/python2.7/logging/__init__.py", line 1528, in basicConfig
  12.    hdlr = FileHandler(filename, mode)
  13.  File "/usr/lib/python2.7/logging/__init__.py", line 901, in __init__
  14.    StreamHandler.__init__(self, self._open())
  15.  File "/usr/lib/python2.7/logging/__init__.py", line 924, in _open
  16.    stream = open(self.baseFilename, self.mode)
  17. IOError: [Errno 13] Permission denied: '/var/log/pi_garage_alert.log'
  18.  
  19. /var/www/pi_garage_alert.py:257: RuntimeWarning: No channels have been set up yet - nothing to clean up!  Try cleaning up at the end of your program instead!
  20.  GPIO.cleanup()
  21. [Fri Aug 01 01:14:21 2014] [error] [client 192.168.1.1] PHP Fatal error:  Maximum execution time of 30 seconds exceeded in /var/www/boton.php on line 4, referer: http://melanoma69.no-ip.biz/
  22. /home/pi/Dropbox-Uploader/dropbox_uploader.sh: line 1036: echo: write error: Broken pipe
  23. /home/pi/Dropbox-Uploader/dropbox_uploader.sh: line 1039: echo: write error: Broken pipe

Muchas gracias
« Última modificación: 1 Agosto 2014, 22:57 pm por #!drvy » En línea

MinusFour
Moderador Global
***
Desconectado Desconectado

Mensajes: 5.529


I'm fourth.


Ver Perfil WWW
Re: Insertar script python en pagina php
« Respuesta #3 en: 1 Agosto 2014, 17:06 pm »

Usa las etiquetas [ code][ /code] para poner códigos largos.

Esto es un problema de permisos en la carpeta /var/www/fotospuerta/ y /var/log/pi_garage_alert.log.

Código
  1. sudo chmod o+w /var/www/fotospuerta/
  2. sudo chmod o+r /var/log/pi_garage_alert.log

Prueba así.
« Última modificación: 1 Agosto 2014, 17:09 pm por MinusFour » En línea

melanoma69

Desconectado Desconectado

Mensajes: 4


Ver Perfil
Re: Insertar script python en pagina php
« Respuesta #4 en: 1 Agosto 2014, 17:24 pm »

Perdon por mi ignorancia pero cuales son los codigos largos?

Despues de poner bien los permisos me siguen saliendo un monton de errores en el log de apache... que desesperacion

Código
  1. /var/www/pi_garage_alert.py:257: RuntimeWarning: No channels have been set up yet - nothing to clean up!  Try cleaning up at the end of your program instead!
  2.  GPIO.cleanup()
  3. [Fri Aug 01 17:22:29 2014] [error] [client 192.168.1.1] PHP Notice:  Undefined index: error in /var/www/index.php on line 16
  4. CRITICAL:root:Terminating due to unexpected error: <type 'exceptions.IOError'>
  5. CRITICAL:root:Traceback (most recent call last):
  6.  File "/var/www/pi_garage_alert.py", line 162, in main
  7.    logging.basicConfig(format=log_fmt, level=log_level, filename=cfg.LOG_FILENAME)
  8.  File "/usr/lib/python2.7/logging/__init__.py", line 1528, in basicConfig
  9.    hdlr = FileHandler(filename, mode)
  10.  File "/usr/lib/python2.7/logging/__init__.py", line 901, in __init__
  11.    StreamHandler.__init__(self, self._open())
  12.  File "/usr/lib/python2.7/logging/__init__.py", line 924, in _open
  13.    stream = open(self.baseFilename, self.mode)
  14. IOError: [Errno 13] Permission denied: '/var/log/pi_garage_alert.log'
  15.  
  16. /var/www/pi_garage_alert.py:257: RuntimeWarning: No channels have been set up yet - nothing to clean up!  Try cleaning up at the end of your program instead!
  17.  GPIO.cleanup()
« Última modificación: 1 Agosto 2014, 22:57 pm por #!drvy » En línea

MinusFour
Moderador Global
***
Desconectado Desconectado

Mensajes: 5.529


I'm fourth.


Ver Perfil WWW
Re: Insertar script python en pagina php
« Respuesta #5 en: 1 Agosto 2014, 17:57 pm »

Por alguna razon necesitas mas pemisos para abrir el archivo /var/log/pi_garage_alert.log

¿Si existe el archivo verdad? Prueba darle permisos de escritura tambien:

Código
  1. chmod o+w /var/log/pi_garage_alert.log
En línea

melanoma69

Desconectado Desconectado

Mensajes: 4


Ver Perfil
Re: Insertar script python en pagina php
« Respuesta #6 en: 1 Agosto 2014, 18:13 pm »

Si que existe, ahora en el log no pone nada, así que supongo que eso es bueno y que esta arreglado. El problema es que no hace nada cuando pincho en mi web sobre boton.php

boton.php activa pi_garage_alert.py (cuando un magnético de puerta se activa) a su vez activa intentofoto.py

El tema es que en el terminal funciona de lujo

Gracias
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
¿Como insertar ascii en consola python?
Scripting
@ron 2 4,651 Último mensaje 14 Diciembre 2009, 22:24 pm
por @ron
[Python] Abrir una página web con comandos de Python. « 1 2 3 4 »
Scripting
CaronteGold 31 39,382 Último mensaje 29 Mayo 2015, 15:02 pm
por antkk
Insertar variables en SQLITE3 Python
Scripting
CaronteGold 4 5,771 Último mensaje 13 Septiembre 2010, 01:32 am
por CaronteGold
Script para insertar chat IRC en una web cualquiera (javascript)
Desarrollo Web
iDrokerGeek_ 0 2,077 Último mensaje 21 Junio 2013, 13:39 pm
por iDrokerGeek_
Insertar <Script> en VB.NET
.NET (C#, VB.NET, ASP)
SγиtαxEяяoя 5 4,090 Último mensaje 28 Junio 2013, 22:58 pm
por BlackM4ster
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines