Форум сайта python.su
В статье «CGI: пишем простой сайт на Python. Часть 1: Hello world» (https://pythonworld.ru/web/cgi-1.html) описывается, каким образом производить запуск CGI-скриптов на языке Python с помощью локального сервера, но если такой же файл запустить из аналогичного каталога (cgi-bin) сервера Apache (ОС Linux), то в браузере вместо искомой фразы Hello world! выдаётся содержимое этого файла. Между тем, CGI-скрипты на языке Pascal на данном сервере работают корректно. Что же необходимо сделать, чтобы и CGI-скрипты на языке Python были работоспособны не только на локальном сервере? Заранее признателен за любой совет по изложенной проблеме.
Офлайн
vadval15Надо установить право выполения на сам скрипт. Убедись, что пользователь, под которым запускается Apache сервер, может выполнить скрипт на питоне. Для этого можно использовать (если пользователь apache)
Что же необходимо сделать, чтобы и CGI-скрипты на языке Python были работоспособны не только на локальном сервере?
sudo -u apache путь_к_скрипту/script.py
Отредактировано py.user.next (Авг. 11, 2019 16:01:04)
Офлайн
Спасибо за ответ. К сожалению, ни установка полных прав на скрипт, ни замена пользователя не привели к положительным результатам.
Офлайн
Ну давай конкретную конфигурацию.
Опиши, как ты запускаешь скрипт (что в браузере вводишь), что ты видишь при этом (что браузер выводит в ответ).
Потом напиши, где располагается скрипт (в какой директории), приведи дерево директорий сервера.
И потом там ещё в директории со скриптом выполни команду
ls -l
Отредактировано py.user.next (Авг. 12, 2019 03:49:02)
Офлайн
Спасибо за ответ. Конкретная конфигурация следующая:
1. Запуск скрипта:
http://mysite.com/cgi-bin/script.py
итого 202456 -rwxr-xr-x 1 user user 2358000 авг 15 2017 cgiproject00o.cgi -rwxr-xr-x 1 user user 2346480 апр 15 2018 cgiproject00op.cgi -rwxr-xr-x 1 user user 2360176 авг 16 2017 cgiproject01o.cgi -rwxr-xr-x 1 user user 2173488 июн 3 2018 cgiproject0cp.cgi -rwxr-xr-x 1 user user 2385724 авг 1 2018 cgiproject0o.cgi -rwxr-xr-x 1 user user 2178584 янв 10 2019 cgiproject0og.cgi -rwxr-xr-x 1 user user 2332104 янв 10 2019 cgiproject0op.cgi -rwxr-xr-x 1 user user 16411996 июл 21 2018 cgiproject0oz.cgi -rwxr-xr-x 1 user user 2391160 авг 8 2018 cgiproject0p.cgi -rwxr-xr-x 1 user user 2417864 авг 24 2017 cgiproject1cak.cgi -rwxr-xr-x 1 user user 2231400 июн 10 2018 cgiproject1cap.cgi -rwxr-xr-x 1 user user 2443408 авг 1 2018 cgiproject1c.cgi -rwxr-xr-x 1 user user 2319812 июн 3 2018 cgiproject1cp.cgi -rwxr-xr-x 1 user user 2621928 авг 1 2018 cgiproject1o.cgi -rwxr-xr-x 1 user user 2410680 янв 10 2019 cgiproject1og.cgi -rwxr-xr-x 1 user user 2564356 янв 10 2019 cgiproject1op.cgi -rwxr-xr-x 1 user user 16643060 июл 21 2018 cgiproject1oz.cgi -rwxr-xr-x 1 user user 2643320 авг 8 2018 cgiproject1p.cgi -rwxr-xr-x 1 user user 2762812 авг 10 04:18 cgiproject1pp.cgi -rwxr-xr-x 1 user user 2161596 июн 10 2018 cgiproject2cap.cgi -rwxr-xr-x 1 user user 2373604 авг 1 2018 cgiproject2c.cgi -rwxr-xr-x 1 user user 2314248 июн 10 2018 cgiproject2cp.cgi -rwxr-xr-x 1 user user 2620808 авг 1 2018 cgiproject2o.cgi -rwxr-xr-x 1 user user 2409520 янв 10 2019 cgiproject2og.cgi -rwxr-xr-x 1 user user 2563188 янв 10 2019 cgiproject2op.cgi -rwxr-xr-x 1 user user 16642672 июл 21 2018 cgiproject2oz.cgi -rwxr-xr-x 1 user user 1722716 авг 8 2018 cgiproject2p.cgi -rwxr-xr-x 1 user user 2762812 авг 10 04:18 cgiproject2pp.cgi -rwxr-xr-x 1 user user 2547724 авг 1 2018 cgiproject3o.cgi -rwxr-xr-x 1 user user 2340716 янв 10 2019 cgiproject3og.cgi -rwxr-xr-x 1 user user 2494260 янв 10 2019 cgiproject3op.cgi -rwxr-xr-x 1 user user 16573060 июл 21 2018 cgiproject3oz.cgi -rwxr-xr-x 1 user user 2735604 авг 8 2018 cgiproject3pu.cgi -rwxr-xr-x 1 user user 3047576 авг 1 2018 cgiproject4o.cgi -rwxr-xr-x 1 user user 2444600 янв 10 2019 cgiproject4og.cgi -rwxr-xr-x 1 user user 2598492 янв 10 2019 cgiproject4op.cgi -rwxr-xr-x 1 user user 16681500 июл 21 2018 cgiproject4oz.cgi -rwxr-xr-x 1 user user 2769340 авг 8 2018 cgiproject4pu.cgi -rwxr-xr-x 1 user user 2619120 авг 9 2018 cgiproject5ap.cgi -rwxr-xr-x 1 user user 2524544 авг 1 2018 cgiproject5o.cgi -rwxr-xr-x 1 user user 2317576 янв 10 2019 cgiproject5og.cgi -rwxr-xr-x 1 user user 2467080 янв 10 2019 cgiproject5op.cgi -rwxr-xr-x 1 user user 16550556 июл 21 2018 cgiproject5oz.cgi -rwxr-xr-x 1 user user 2619248 авг 9 2018 cgiproject5p.cgi -rwxr-xr-x 1 user user 1699480 авг 9 2018 cgiproject6ap.cgi -rwxr-xr-x 1 user user 1695012 авг 9 2018 cgiproject6p.cgi -rwxr-xr-x 1 user user 2708332 авг 9 2018 cgiproject7apu.cgi -rwxr-xr-x 1 user user 2704188 авг 9 2018 cgiproject7pu.cgi -rwxr-xr-x 1 user user 2727384 авг 9 2018 cgiproject8apu.cgi -rwxr-xr-x 1 user user 2725120 авг 9 2018 cgiproject8pu.cgi -rwxr-xr-x 1 user user 626 авг 8 04:05 cgipyth1p.cgi -rwxr-xr-x 1 user user 734 авг 11 09:49 cgipyth1p.py -rwxr-xr-x 1 user user 143 авг 11 10:46 cgipyth1.py -rwxrwxr-x 1 user user 436 авг 11 11:45 exe2.py -rwxrwxr-x 1 user user 265 авг 11 11:57 exe3.py -rwxrwxr-x 1 user user 86 авг 11 12:00 exe4.py -rwxrwxr-x 1 user user 174 авг 12 02:28 hello11.py -rwxrwxr-x 1 user user 209 авг 11 14:00 hello1.py -rwxrwxr-x 1 user user 182 авг 11 10:51 hello2.py -rwxrwxr-x 1 user user 204 авг 12 02:16 hello3.py -rwxrwxr-x 1 user user 171 авг 12 02:17 hello4.py -rwxrwxr-x 1 user user 170 авг 8 16:16 mptest.py lrwxrwxrwx 1 root root 35 июл 1 2018 printenv -> /usr/share/apache2/cgi-bin/printenv -rwxr-xr-x 1 user user 207 авг 9 02:11 pythex1.py lrwxrwxrwx 1 root root 35 июл 1 2018 test-cgi -> /usr/share/apache2/cgi-bin/test-cgi
1. hello1.py: #!/usr/bin/env python3 import cgitb cgitb.enable() print("Content-type: text/html\n\n") print("<html><head><title>Python test</title></head><body>") print("<h1>Hello world!</h1>") print("</body></html>") 2. hello2.py: #!/usr/bin/env python3 print("Content-type: text/html") print() print("<html><head><title>Python test</title></head><body>") print("<h1>Hello world!</h1>") print("</body></html>") 3. hello3.py: #!/usr/bin/env python import cgitb cgitb.enable() print "Content-type: text/html\n\n" print "<html><head><title>Python test</title></head><body>" print "<h1>Hello world!</h1>" print "</body></html>" 4. hello4.py: #!/usr/bin/python print "Content-type: text/html" print print "<html><head><title>Python test</title></head><body>" print "<h1>Helo world!</h1>" print "</body></html>"
1. cgi-load: LoadModule cgi_module /usr/lib/apache2/modules/mod_cgi.so 2. default.conf: # # Summary: Main server configuration (for default virtual host) # Provides: VirtualHost # Provides: VirtualHost-default # # # 'Main' server configuration # # The directives in this section set up the values used by the 'main' # server, which responds to any requests that aren't handled by a # <VirtualHost> definition. These values also provide defaults for # any <VirtualHost> containers you may define later in the file. # # All of these directives may appear inside <VirtualHost> containers, # in which case these default settings will be overridden for the # virtual host being defined. # <VirtualHost *> # # ServerAdmin: Your address, where problems with the server should be # e-mailed. This address appears on some server-generated pages, such # as error documents. e.g. admin@your-domain.com # ServerAdmin root@mysite.com # # ServerName gives the name and port that the server uses to identify itself. # This can often be determined automatically, but we recommend you specify # it explicitly to prevent problems during startup. # # If your host doesn't have a registered DNS name, enter its IP address here. # ServerName mysite.com:80 # # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # DocumentRoot "/var/www/apache2/html" # # Each directory to which Apache has access can be configured with respect # to which services and features are allowed and/or disabled in that # directory (and its subdirectories). # # First, we configure the "default" to be a very restrictive set of # features. # <Directory /> # Summary: Configure for all dirs by default # Requires: Directory-root Include conf/include/Directory_root_default.conf </Directory> # # Note that from this point forward you must specifically allow # particular features to be enabled - so if something's not working as # you might expect, make sure that you have specifically enabled it # below. # # # This should be changed to whatever you set DocumentRoot to. # <Directory "/var/www/apache2/html"> # Summary: Configure for html documents in DocumentRoot # Requires: Directory-html Include conf/include/Directory_html_default.conf </Directory> # # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a <VirtualHost> # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a <VirtualHost> # container, that host's errors will be logged there and not here. # ErrorLog /var/log/httpd2/error_log # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn <IfModule log_config_module> # # The location and format of the access logfile (Common Logfile Format). # If you do not define any access logfiles within a <VirtualHost> # container, they will be logged here. Contrariwise, if you *do* # define per-<VirtualHost> access logfiles, transactions will be # logged therein and *not* in this file. # CustomLog /var/log/httpd2/access_log common # # If you prefer a logfile with access, agent, and referer information # (Combined Logfile Format) you can use the following directive. # #CustomLog /var/log/httpd2/access_log combined </IfModule> <IfModule alias_module> # # Redirect: Allows you to tell clients about documents that used to # exist in your server's namespace, but do not anymore. The client # will make a new request for the document at its new location. # Example: # Redirect permanent /foo http://www.example.com/bar # # Alias: Maps web paths into filesystem paths and is used to # access content that does not live under the DocumentRoot. # Example: # Alias /webpath /full/filesystem/path # # If you include a trailing / on /webpath then the server will # require it to be present in the URL. You will also likely # need to provide a <Directory> section to allow access to # the filesystem path. # # ScriptAlias: This controls which directories contain server scripts. # ScriptAliases are essentially the same as Aliases, except that # documents in the target directory are treated as applications and # run by the server when requested rather than as documents sent to the # client. The same rules about trailing "/" apply to ScriptAlias # directives as to Alias. # ScriptAlias /cgi-bin/ "/var/www/apache2/cgi-bin/" </IfModule> # # "/var/www/cgi-bin" should be changed to whatever your ScriptAliased # CGI directory exists, if you have that configured. # <Directory "/var/www/apache2/cgi-bin"> # Summary: Configure for default CGI directory # Requires: Directory-cgi Include conf/include/Directory_cgibin_default.conf </Directory> </VirtualHost> 3. httpd-mime.conf: # # Summary: Configure the list of mappings from filename extension to MIME-type. # Provides: Extra # <IfModule mime_module> # # AddType allows you to add to or override the MIME configuration # file specified in TypesConfig for specific file types. # #AddType application/x-gzip .tgz # # AddEncoding allows you to have certain browsers uncompress # information on the fly. Note: Not all browsers support this. # #AddEncoding x-compress .Z #AddEncoding x-gzip .gz .tgz # # If the AddEncoding directives above are commented-out, then you # probably should define those extensions to indicate media types: # AddType application/x-compress .Z AddType application/x-gzip .gz .tgz # # AddHandler allows you to map certain file extensions to "handlers": # actions unrelated to filetype. These can be either built into the server # or added with the Action directive (see below) # # To use CGI scripts outside of ScriptAliased directories: # (You will also need to add "ExecCGI" to the "Options" directive.) # AddHandler cgi-script .cgi .py # For type maps (negotiated resources): #AddHandler type-map var # # Filters allow you to process content before it is sent to the client. # # To parse .shtml files for server-side includes (SSI): # (You will also need to add "Includes" to the "Options" directive.) # AddType text/html .shtml <IfModule include_module> AddOutputFilter INCLUDES .shtml </IfModule> </IfModule> 4. Directory_cgibin_default.conf: # # Summary: Default config for CGI directory # Provides: Directory # Provides: Directory-cgi # # # "/var/www/cgi-bin" should be changed to whatever your ScriptAliased # CGI directory exists, if you have that configured. # Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Require all granted 5. Directory_html_default.conf: # # Summary: Default config for html documents # Provides: Directory # Provides: Directory-html # # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#options # for more information. # Options Includes FollowSymLinks ExecCGI MultiViews # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride None # # Controls who can get stuff from this server. # Require all granted 6. ports_all.conf: # # Summary: Use name-based virtual hosting for * # Provides: NameVirtualHost # # # Use name-based virtual hosting. # NameVirtualHost *:80
Отредактировано vadval15 (Авг. 12, 2019 15:19:22)
Офлайн
vadval15А я вот не вижу у тебя скрипта script.py там в директории. Значит, ты пишешь неточно. То есть мы должны догадаться, что ты запускаешь не так, а по-другому как-то. То же само с конфигами сервера: ты пишешь их в виде смеси, а мы должны догдаться, что они не смешаны у тебя, а лежат раздельно. Учись писать точно. Любая неточная мелочь может играть вообще ключевую роль.
1. Запуск скрипта:http://mysite.com/cgi-bin/script.py
cd /
sudo -u user /var/www/apache2/cgi-bin/hello2.py
Отредактировано py.user.next (Авг. 13, 2019 02:17:27)
Офлайн
Спасибо за ответ. Я полагал, что указание в вызове вместо какого-то определённого имени собирательного имени скрипта, которое само по себе никак не влияет на его функциональность, должно быть для всех очевидным, но ошибся. В связи с этим приношу свои извинения. В списке конфигурационных файлов сервера Apache приведены только те, которые, с моей точки зрения, могут представлять интерес, их расположение в файловой системе остаётся неизменным со времени установки самого сервера. В отношении же первоначального вопроса мною была сделана попытка как дополнительного варианта настройки модуля mod_python. В процессе этой настройки я случайно вместо отлаживаемого MOD-скрипта вызвал CGI-скрипт, и неизвестно по какой причине он начал корректно работать. Как выяснилось, так же корректно ни с того, ни с сего заработали и другие CGI-скрипты на языке Python, хотя до этого систематически выдавали неправильный результат. Так что описанная ранее проблема непонятным образом разрешилась сама собой, сыграл ли в этом какую-либо роль модуль mod_python - мне трудно сказать. Тем не менее, я очень признателен за оказанную мне моральную и информационную поддержку.
Офлайн
vadval15Всё по той же причине он начал работать. Ты думал одно и тебе казалось что-то стопроцентно, а делал ты другое. Стоит только сделать именно то, что думаешь, а не что-то похожее на то же самое и кажущееся правильным, так сразу вылазит ошибка, закравшаяся в этой уверенной эквивалентной связи, которая оказывается ложной.
В процессе этой настройки я случайно вместо отлаживаемого MOD-скрипта вызвал CGI-скрипт, и неизвестно по какой причине он начал корректно работать.
vadval15Это ложное предположение. А когнитивное искажение это называется “чтением мыслей”. Тебе кажется, что мы думаем “вот так-то”, как тебе кажется, каким образом мы думаем, а в это время мы думаем вообще по-другому и другими конструкциями, которые тебе неизвестны. Даже приблизительно ты не знаешь объём того множества гипотез, которые мы построили и про твой сервер, и про твои скрипты ещё по первому сообщению в топике. Мы и не должны тебе о них сообщать, потому что большинство их них ложны и требуют просто проверки.
Я полагал, что указание в вызове вместо какого-то определённого имени собирательного имени скрипта, которое само по себе никак не влияет на его функциональность, должно быть для всех очевидным
Отредактировано py.user.next (Авг. 14, 2019 07:41:48)
Офлайн
Спасибо за обстоятельный ответ. В самом деле, мне очень жаль, что я своими своевольными действиями не дал продемонстрировать возможности вашей хорошо отрегулированной системы поиска и исправления ошибок и необдуманным вовлечением вас в хаос своих умозаключений нарушил весь ход работы гигантского механизма по построению и проверке всевозможных гипотез по поводу некорректной работы своего сервера и скриптов. С другой стороны, вы чётко определили причину моих ошибок и неудач, а также неожиданно успешного начала работы скриптов, которое при любом анализе всё же трудно назвать настоящим тупиком, что хоть в какой-то степени может послужить оправданием мне и утешением вам.
Офлайн
vadval15Да, у тебя бардак и в голове, и в операционной системе. И ты пытаешься нам вот этот свой бардак навязать, будто это нормально; будто нормально, когда в системе 100500 файлов с одним именем, совершенно не информативным, когда конфиги лежат смешанными в одном месте, когда в самих конфигах просто свалка из разных, несгруппированных настроек и тому подобное. И когда тебе говорят “дорогуша, на профессиональных форумах/трекерах/ресурсах так не общаются”, ты начинаешь обижаться. Вот мол не оценили твой профессионализм. Твоим уровнем профессионализма веет за километр, с самого первого сообщения, в котором ты не выложил ничего, чтобы решать твою проблему. И мне пришлось ещё у тебя эту информацию запрашивать дополнительно, которую ты должен был выложить сам, если ты профессионал, а не какой-то дешёвый дурачок из какой-то говнофирмы, вероятно, и бюджетной к тому же. Кстати, Object Pascal, про который ты тут так многозначительно упоминал, уже лет двадцать никому нафиг не упёрся, потому что уже изобрели и развили десяток языков, каждый из которых лучше него. Ты его просто нигде не встретишь. Ну кроме как…
С другой стороны, вы чётко определили причину моих ошибок и неудач
Отредактировано py.user.next (Авг. 15, 2019 06:28:36)
Офлайн