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

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


  Mostrar Temas
Páginas: [1]
1  Programación / PHP / 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
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines