Apache python cgi linux

CGI Apache настройка отдачи cgi скриптов

Потребуется написать простейший CGI скрипт — сделаем это на bash, также нужно активировать соответствующий модуль Apache.

Прежде всего приводим конфигурационный файл дефолтного виртуального хоста apache2 в соответствие приведенному ниже образцу

ServerName www.example.com

ServerAdmin webmaster@localhost
DocumentRoot /var/www/html

ErrorLog $/error.log
CustomLog $/access.log combined

ScriptAlias /cgi-bin/ /var/www/cgi-bin/

Options +Indexes
Options +ExecCGI
AddHandler cgi-script .cgi

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

Опционально — в /etc/hosts добавляем строку, согласно которой при обращении к www.example.com будет задействоваться вирт. хост на локальной машине

127.0.01 www.example.com

Включаем модуль веб-сервера и перезапускаем сервер

Создаем каталог, в котором будут размещаться скрипты и переходим в него

Далее нужно написать какой-то скрипт. Пусть он выводит слово hello и актуальное время обращения к скрипту

#!/bin/bash
echo Content-type: text/plain
echo «»

echo «hello»

Как любой bash скрипт он должен быть исполняемым

Настройка CGI Apache на этом завершена — теперь в браузере достаточно обратиться по адресу localhost/cgi-bin/script.cgi чтобы увидеть результат.

Поскольку ранее в /etc/hosts добавили нужное правило тот же вывод можно получить обратившись к www.example.com/cgi-bin/script.cgi

CGI скрипты требуют прав на исполнение и небезопасны, если скрипт написан плохо ему можно передать любые параметры и получить доступ к хост системе сервера. CGI в настоящее время используется ограниченно, в основном для административных скриптов, для сайтов применяется более безопасный способ исполнения — fastcgi

Источник

Создание виртуальных хостов в apache под Linux на Python

Занимаюсь разработкой сайтов и всякие эксперименты и основную разработку делаю на локальном компьютере под Debian. В следствии того, что приходилось постоянно ручками создавать виртуальные хосты пришлось поставить себе цель автоматизировать процесс.
Первый делом двинулся я в просторы интернета в поисках необходимого решения, которое должно было обладать простотой и выполнять всего 2 задачи: добавлять виртуальный хост и удалять его. Мне удобно пользоваться консолью, поэтому и приложение должно было быть консольным. Но все варианты которые нашел имели большое количество ненужного функционала, кроме того почти все они предоставляли web интерфейс, которым я просто не хотел пользоваться.
В результате были поставлены цели:
— написать свой простенький скрипт, который создавал все то, что мне нужно;
— в качестве языка разработке я выбрал python, т.к. давно искал повод на нем учится писать.

Update (08.09.11 20:25): учитывая ошибки в комментариях немного исправил скрипт. Начал использовать optparse, сократил использование .write.

В результате я получил полностью удовлетворяющий меня скрипт под катом.

Примечания к скрипту

В связи с предназначением скрипта, он запускается под root`om или через sudo.

Мини инструкция, для тех кто не дойдет до -help:
Usage: script [options] [add|drop] domain
В опциях изменяются настройки для работы скрита.

Во время добавления либо удаления домена:
— вносится изменение в hosts файл, для внесении информации о домене;
— в директориях переданных через dir_site создаются необходимые файлы и папки для нашего домена;
— в директории указанной в apache_config_site создается файл с конфигурацией virtualhost для apache.

Источник

Apache python cgi linux

Depending on the Linux distro and even the version the name and path of the apache config file will be different. You did not specify which distro you were running on.

I can only say regarding ubuntu and LAMP as that is what i have created servers on numerous times. Since you did not specify which distro you were on. from this point on ill assume your on ubuntu. As it is the most used.

1) You have to install AND enable the cgi_mod
enable it
2) create and change your permissions for the cgi directory
(change path to where ever you want it, but you need to add a script alias if you change it from default /usr/lib/cgi-bin)
2) In your apache config file you have to add a directory to the planned CGI directory. The best way to explain that is to use an example.

This is my /etc/apache2/apache2.conf directory adding for my cgi directory
This is my directory listing for my cgi directory which is /var/www/html/cgi-bin. The scriptalias line enables this directory path. The main points are Options +ExecCGI and the addhandler for .py whihc enable you to run cgi scripts. Save this in your apache config file.

Restart apache.
Close the old browser and start anew after.

Then on your scripts.
make sure to add a shebang line
As well as cgitb to allow you to view tracebacks through the browser
If you do not do this you might get an internal server error because you typo’d something and now cannot see the traceback to point you to your python script error. If you do not do this you can still view the traceback through the error logs. Create a second terminal to the server (or just use tmux to split the terminal) and execute
before you execute your python script to view the traceback in the error logs

And the first line printed must be
and you might as well make it as organized as possible by using the format method to insert values into your html such as.

html = «»»Content-type: text/html\n Python Porting Guide


Input all or a portion of the known syntax for either Python2.x or Python3.x
Results are based only on version differences, not every module in existence to python

Источник

How do I run python cgi script on apache2 server on Ubuntu 16.04?

I am a newbie so I saw some tutorials. I have a python script as first.py

#!/usr/bin/python3 print «Content-type: text/html\n» print «Hello, world!»

I have multiple versions of python on my computer. I couldn’t figure out my cgi enabled directory so I pasted this code at three places

Now when I run this code in terminal it works fine but when I type

it spit out just simple text and does not execute.

I have given all the permissions to first.py

I have enabled and started the server by commands

a2enmod cgi systemctl restart apache2

Please tell how do I execute and what is going on here? Thanks in advance.

3 Answers 3

To python cgi script on apache2 server on Ubuntu(Tested on Ubuntu 20.04) from scratch, Follow these steps(Expects python is installed and works perfectly).

Install apache2 sever.

Enable CGI module.

Here we set /var/www/cgi-bin/ as cgi-bin directory. If you want a different directory, change files appropriately.

Open Apache server configuration file [ /etc/apache2/apache2.conf ] by,

And following lines to the end of the file.

Open file /etc/apache2/conf-available/serve-cgi-bin.conf by,

Now restart apache2 server by,

Источник

Run Python script as CGI program with Apache2 in Linux / Wamp in Windows

If you’ve Apache & Python installed, you can execute your python scripts as CGI programs, which your visitors can access if you host the scripts in a server. You can write your scripts in python (file-name will end with .py) or in perl (extention .pl) or anything else which is compatible.

Step 1 – Write a “Hello, World! ” script in Python

In a text editor, type following code. Give the file name “first.py

The first line is important – it tells where in our computer Python is available. If you’re using windows, use appropriate location, for example, change the first line to something like:

Step 2 – Put the script in a suitable directory

Important: If you are in Linux, make your file executable! Type:

  1. Let’s rename the file to first.py and make it executable, if we’re in Linux.
  2. Put it in a directory named “cgi-bin” under our document root. Then, the file may be accessed in the web-browser by simply typing: http://localhost/cgi-bin/first.py

Step 3 – Configure Apache2

Next step is to configure Apache so that it treats our file as a CGI program. Go to the directory where your Apache configuration file exists. In Linux, it resides under /etc/apache2/ and the configuration file is httpd.conf

NOTE: If virtual hosts are enabled (normally the are enabled), changing the httpd.conf will have no effect. You may need to edit particular configuration file for the site which is enabled. Go to the sites-enabled directory and open the file which is currently enabled (If you have only the file “default” in your /etc/apache2/sites-enabled directory, you should open this file with your text editor)

NOTE: If you are in windows, and using Wamp, you can simply open the httpd.conf file and make following changes.

Edit the configuration file:

Search for the line: ScriptAlias /cgi-bin/ /whatever-path/ – when you find it, comment out the line: that is add a # in front of the line:

Then, paste following lines of code:

If your first.py is in /var/www/cgi-bin/ folder, then replace the first line by

You’re done! Now restart Apache to activate all changes.

If you’re in Linux, open a terminal and enter sudo /etc/init.d/apache2 reload to restart Apache. If you’re using Wamp in Windows, you can restart Apache clicking appropriate icons!

Fire up your web browser, type http://localhost/cgi-bin/first.py and hit Enter…

If you find only the text:

in the page, then congratulations!

If you find any other text than Hello, world!, something went wrong. Check for your mistakes. Ensure that “cgi_module” Apache module is enabled.

Источник

Читайте также:  Windows spider solitaire free
Оцените статью