The OpenNET Project / Index page

[ новости /+++ | форум | теги | ]




Версия для распечатки Пред. тема | След. тема
Новые ответы [ Отслеживать ]
Как выполнить программу или shell скрипт из PHP?, !*! termsl, 03-Авг-07, 10:23  [смотреть все]
Есть страничка:

Код:

<html><body>
<?php
echo "Start 2\n";
echo exec('date');
echo exec('/bin/comonn');
echo exec('comonn');
?>
</body></html>


/bin/comonn - моя программа / скрипт по указанному (произвольному, не обязательно /bin пути, копия лежит в папке c index.php, существует, права 0777, в ручную и из shell скрипта работает
Apache 2.2.
PHP 5.5.
FreeBSD 6.1-RELEASE #0

При открытии данной страницы выводится старт, результат выполнения date ...... и все....

  • Как выполнить программу или shell скрипт из PHP?, !*! XAnder, 10:58 , 03-Авг-07 (1)
    Функция exec возвращает не весь вывод программы, а только последнюю строку. Возможно здесь она пустая. Попробуйте вместо echo exec(...) сделать system(...). А чтобы отследить ход выполнения программы, перед каждым действием добавьте что-то вроде echo("Делаю то-то и то-то..."), по крайней мере будет видно, какой оператор что выводит.
    • Как выполнить программу или shell скрипт из PHP?, !*! termsl, 12:08 , 03-Авг-07 (2)
      system (); пробовал - тот же результат, у комманды есть вывод в последней строке

      если сделать так:

      # php ./index.php - то все отрабатывается и выводится, такое ощущение - что апач встал в позу

      • Как выполнить программу или shell скрипт из PHP?, !*! XAnder, 12:45 , 03-Авг-07 (3)
        >если сделать так:
        ># php ./index.php - то все отрабатывается и выводится, такое ощущение -
        >что апач встал в позу

        Какие права выставлены на /bin/comonn?

        На всякий случай проверьте disable_functions в php.ini, нет ли там exec.

        • Как выполнить программу или shell скрипт из PHP?, !*! termsl, 12:55 , 03-Авг-07 (4)
          php.ini:
          disable_functions =


          права выставлены на /bin/comonn  - 0777

          Притом комманда, выполненная из shell:

          #php ./index.php

          все отлично отрабатывает и выводит, собственно PHP не причем .....

          • Как выполнить программу или shell скрипт из PHP?, !*! XAnder, 15:37 , 03-Авг-07 (5)
            У меня идеи потихоньку заканчиваются - не взыщите. Из безумных вот:

            1. Апач случайно не в chroot'е работает?

            2. Не запускает ли он PHP в Safe mode? Если так, то что указано в safe_mode_exec_dir в php.ini?

            3. Ваша программа comonn чувствительна ли к пользователю, который её запускает? Может, если её запустит апачевский юзер, то она ведёт себя как-то не так?

            • Как выполнить программу или shell скрипт из PHP?, !*! termsl, 02:36 , 04-Авг-07 (6)
              >У меня идеи потихоньку заканчиваются - не взыщите. Из безумных вот:
              >
              >1. Апач случайно не в chroot'е работает?
              >
              >2. Не запускает ли он PHP в Safe mode? Если так, то
              >что указано в safe_mode_exec_dir в php.ini?
              >
              >3. Ваша программа comonn чувствительна ли к пользователю, который её запускает? Может,
              >если её запустит апачевский юзер, то она ведёт себя как-то не
              >так?

              Не chroot ..

              Apache 2.2.
              PHP 5.5.
              FreeBSD 6.1-RELEASE #0

              php.ini :

              ///////////////////////////////////////////////////cut
              safe_mode = Off

              ; By default, Safe Mode does a UID compare check when
              ; opening files. If you want to relax this to a GID compare,
              ; then turn on safe_mode_gid.
              safe_mode_gid = Off

              ; When safe_mode is on, UID/GID checks are bypassed when
              ; including files from this directory and its subdirectories.
              ; (directory must also be in include_path or full path must
              ; be used when including)
              safe_mode_include_dir =

              ; will be allowed to be executed via the exec family of functions.
              safe_mode_exec_dir =
              ; When safe_mode is on, only executables located in the safe_mode_exec_dir
              ; will be allowed to be executed via the exec family of functions.
              safe_mode_exec_dir =

              ; Setting certain environment variables may be a potential security breach.
              ; This directive contains a comma-delimited list of prefixes.  In Safe Mode,
              ; the user may only alter environment variables whose names begin with the
              ; prefixes supplied here.  By default, users will only be able to set
              ; environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).
              ;
              ; Note:  If this directive is empty, PHP will let the user modify ANY
              ; environment variable!
              safe_mode_allowed_env_vars = PHP_

              ; This directive contains a comma-delimited list of environment variables that
              ; the end user won't be able to change using putenv().  These variables will be
              ; protected even if safe_mode_allowed_env_vars is set to allow to change them.
              safe_mode_protected_env_vars = LD_LIBRARY_PATH
              ///////////////////////////////////////////////////cut

              Программа скомпиленная GCC: (comonn) (посылает пакеты из 8 байт в СОМ порт - на входе последовательность пакетов по три символа, программа обрамляет пакеты приставкой и окончанием:

              /*
                      *       gcc -O2 -o /test/COM/com /test/COM/com.c
                      */


                      #include <stdio.h>   /* Standard input/output definitions */
                      #include <string.h>  /* String function definitions */
                      #include <unistd.h>  /* UNIX standard function definitions */
                      #include <fcntl.h>   /* File control definitions */
                      #include <errno.h>   /* Error number definitions */
                      #include <termios.h> /* POSIX terminal control definitions */
                      #include <locale.h>

                      #define MAXL 255                /* макс. длина строки */

                      /*
                      * 'open_port()' - Open serial port 1.
                      *
                      * Returns the file descriptor on success or -1 on error.
                      */

              int open_port(void)
                      {
                      int fd;                         /* File descriptor for the port */
                      struct termios options;

                      fd = open("/dev/cuad0", O_RDWR | O_NOCTTY | O_NDELAY);
                      if (fd == -1)
                              {
                              /*
                              * Could not open the port.
                              */
                              perror("open_port: Unable to open /dev/cuad0 :( ");
                              }
                      else
                      {
                      fcntl(fd, F_SETFL, 0);
                      printf ("Port OPEN OK!:>\n");
                      }

                      tcgetattr(fd, &options);
                      cfsetispeed(&options, B57600);
                      cfsetospeed(&options, B57600);
                      tcsetattr(fd, TCSANOW, &options);


                      return (fd);
              }

              int main (argc, argv)  char **argv;
                      {
                      int fdd;
                      int n;
                      char str[10];

                      printf("\n^^^^^^^^^^^^^^^^^^^^^^^^^^\n|    (c) Termsl' 2007    |\n-------------------------\n");

                      fdd = open_port();
                      setlocale(LC_ALL, "");
                      if( argc == 1 )
                              {

                                                      /* программа вызвана без аргументов */
                              }else{                  /* аргументы программы - имена файлов */

                              while( argv[ 1 ] )
                              {
                              printf("<%s> ",argv[1]);
                              n = write(fdd," <!",3);
                              n = write(fdd,argv[1], 8);
                              n = write(fdd,"> ",2);

                              argv++;
                              argc--;
                              }
                      }
                      if (n < 0) fputs("write() failed!\n", stderr);
                      close(fdd);
                      printf ("\n<: Port CLOSED OK! \n=========================\n\n");

                      exit(0);
              }

              собирал под root, потом:


              положил comonn в / сделал
              chmod 0777 /comonn
              chown www /comon

              в index.php поменял пути .... таже ерунда
              также клал в одну папку s index.php....




Партнёры:
PostgresPro
Inferno Solutions
Hosting by Hoster.ru
Хостинг:

Закладки на сайте
Проследить за страницей
Created 1996-2024 by Maxim Chirkov
Добавить, Поддержать, Вебмастеру