質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Apache

Apacheは、Apache HTTP Serverの略で、最も人気の高いWebサーバソフトウェアの一つです。安定性が高いオープンソースソフトウェアとして商用サイトから自宅サーバまで、多くのプラットフォーム向けに開発・配布されています。サーバーソフトウェアの不具合(NCSA httpd)を修正するパッチ(a patch)を集積、一つ独立したソフトウェアとして開発されました。

Raspberry Pi

Raspberry Piは、ラズベリーパイ財団が開発した、名刺サイズのLinuxコンピュータです。 学校で基本的なコンピュータ科学の教育を促進することを意図しています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

3回答

16646閲覧

apache2、CGIでpythonが実行されず、ソースが表示されてしまいます

bin_300K

総合スコア56

Apache

Apacheは、Apache HTTP Serverの略で、最も人気の高いWebサーバソフトウェアの一つです。安定性が高いオープンソースソフトウェアとして商用サイトから自宅サーバまで、多くのプラットフォーム向けに開発・配布されています。サーバーソフトウェアの不具合(NCSA httpd)を修正するパッチ(a patch)を集積、一つ独立したソフトウェアとして開発されました。

Raspberry Pi

Raspberry Piは、ラズベリーパイ財団が開発した、名刺サイズのLinuxコンピュータです。 学校で基本的なコンピュータ科学の教育を促進することを意図しています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2016/05/13 10:00

###前提・実現したいこと

Raspberry PiでWebサーバーを構築中ですが、
apache2、CGI設定をしたところ、
pythonが実行されず、ソースが表示されてしまうところを改善したいのです。
どなたか改善点わかるかたいらっしゃいますでしょうか。

###発生している問題・エラーメッセージ

発生している問題は上記の症状です。私が行った設定・経緯を下記に書きます。

経緯

Raspberry PiでWebサーバーを構築中ですが、
apache2、CGI設定をしたところ、

経緯1:ドキュメントルート(/var/www/)にディレクトリ/cgi-bin/を作って、そこに以下のソースのテストスクリプトを配置しました。

test.cgiのファイルです↓(ディレクトリ /var/www/cgi-bin/)

python

1#! /usr/bin/env python 2 3print "Content-type: text/html\n" 4print "<html><body>hello python page!</body></html>"

経緯2:apache2.confを下記のようにいじりました(設定ファイル長くてすみません。。。)

apache

1# This is the main Apache server configuration file. It contains the 2# configuration directives that give the server its instructions. 3# See http://httpd.apache.org/docs/2.4/ for detailed information about 4# the directives and /usr/share/doc/apache2/README.Debian about Debian specific 5# hints. 6# 7# 8# Summary of how the Apache 2 configuration works in Debian: 9# The Apache 2 web server configuration in Debian is quite different to 10# upstream's suggested way to configure the web server. This is because Debian's 11# default Apache2 installation attempts to make adding and removing modules, 12# virtual hosts, and extra configuration directives as flexible as possible, in 13# order to make automating the changes and administering the server as easy as 14# possible. 15 16# It is split into several files forming the configuration hierarchy outlined 17# below, all located in the /etc/apache2/ directory: 18# 19# /etc/apache2/ 20# |-- apache2.conf 21# | `-- ports.conf 22# |-- mods-enabled 23# | |-- *.load 24# | `-- *.conf 25# |-- conf-enabled 26# | `-- *.conf 27# `-- sites-enabled 28# `-- *.conf 29# 30# 31# * apache2.conf is the main configuration file (this file). It puts the pieces 32# together by including all remaining configuration files when starting up the 33# web server. 34# 35# * ports.conf is always included from the main configuration file. It is 36# supposed to determine listening ports for incoming connections which can be 37# customized anytime. 38# 39# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/ 40# directories contain particular configuration snippets which manage modules, 41# global configuration fragments, or virtual host configurations, 42# respectively. 43# 44# They are activated by symlinking available configuration files from their 45# respective *-available/ counterparts. These should be managed by using our 46# helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See 47# their respective man pages for detailed information. 48# 49# * The binary is called apache2. Due to the use of environment variables, in 50# the default configuration, apache2 needs to be started/stopped with 51# /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not 52# work with the default configuration. 53 54 55# Global configuration 56# 57 58# 59# ServerRoot: The top of the directory tree under which the server's 60# configuration, error, and log files are kept. 61# 62# NOTE! If you intend to place this on an NFS (or otherwise network) 63# mounted filesystem then please read the Mutex documentation (available 64# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>); 65# you will save yourself a lot of trouble. 66# 67# Do NOT add a slash at the end of the directory path. 68# 69#ServerRoot "/etc/apache2" 70 71# 72# The accept serialization lock file MUST BE STORED ON A LOCAL DISK. 73# 74Mutex file:${APACHE_LOCK_DIR} default 75 76# 77# PidFile: The file in which the server should record its process 78# identification number when it starts. 79# This needs to be set in /etc/apache2/envvars 80# 81PidFile ${APACHE_PID_FILE} 82 83# 84# Timeout: The number of seconds before receives and sends time out. 85# 86Timeout 300 87 88# 89# KeepAlive: Whether or not to allow persistent connections (more than 90# one request per connection). Set to "Off" to deactivate. 91# 92KeepAlive On 93 94# 95# MaxKeepAliveRequests: The maximum number of requests to allow 96# during a persistent connection. Set to 0 to allow an unlimited amount. 97# We recommend you leave this number high, for maximum performance. 98# 99MaxKeepAliveRequests 100 100 101# 102# KeepAliveTimeout: Number of seconds to wait for the next request from the 103# same client on the same connection. 104# 105KeepAliveTimeout 5 106 107 108# These need to be set in /etc/apache2/envvars 109User ${APACHE_RUN_USER} 110Group ${APACHE_RUN_GROUP} 111 112# 113# HostnameLookups: Log the names of clients or just their IP addresses 114# e.g., www.apache.org (on) or 204.62.129.132 (off). 115# The default is off because it'd be overall better for the net if people 116# had to knowingly turn this feature on, since enabling it means that 117# each client request will result in AT LEAST one lookup request to the 118# nameserver. 119# 120HostnameLookups Off 121 122# ErrorLog: The location of the error log file. 123# If you do not specify an ErrorLog directive within a <VirtualHost> 124# container, error messages relating to that virtual host will be 125# logged here. If you *do* define an error logfile for a <VirtualHost> 126# container, that host's errors will be logged there and not here. 127# 128ErrorLog ${APACHE_LOG_DIR}/error.log 129 130# 131# LogLevel: Control the severity of messages logged to the error_log. 132# Available values: trace8, ..., trace1, debug, info, notice, warn, 133# error, crit, alert, emerg. 134# It is also possible to configure the log level for particular modules, e.g. 135# "LogLevel info ssl:warn" 136# 137LogLevel warn 138 139# Include module configuration: 140IncludeOptional mods-enabled/*.load 141IncludeOptional mods-enabled/*.conf 142 143# Include list of ports to listen on 144Include ports.conf 145 146 147# Sets the default security model of the Apache2 HTTPD server. It does 148# not allow access to the root filesystem outside of /usr/share and /var/www. 149# The former is used by web applications packaged in Debian, 150# the latter may be used for local directories served by the web server. If 151# your system is serving content from a sub-directory in /srv you must allow 152# access here, or in any related virtual host. 153<Directory /> 154 Options FollowSymLinks 155 AllowOverride None 156 Require all denied 157</Directory> 158 159<Directory /usr/share> 160 AllowOverride None 161 Require all granted 162</Directory> 163 164<Directory /var/www/> 165 Options Indexes FollowSymLinks 166 AllowOverride None 167 Require all granted 168</Directory> 169 170#<Directory /srv/> 171# Options Indexes FollowSymLinks 172# AllowOverride None 173# Require all granted 174#</Directory> 175 176 177 178 179# AccessFileName: The name of the file to look for in each directory 180# for additional configuration directives. See also the AllowOverride 181# directive. 182# 183AccessFileName .htaccess 184 185# 186# The following lines prevent .htaccess and .htpasswd files from being 187# viewed by Web clients. 188# 189<FilesMatch "^\.ht"> 190 Require all denied 191</FilesMatch> 192 193 194# 195# The following directives define some format nicknames for use with 196# a CustomLog directive. 197# 198# These deviate from the Common Log Format definitions in that they use %O 199# (the actual bytes sent including headers) instead of %b (the size of the 200# requested file), because the latter makes it impossible to detect partial 201# requests. 202# 203# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended. 204# Use mod_remoteip instead. 205# 206LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined 207LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined 208LogFormat "%h %l %u %t \"%r\" %>s %O" common 209LogFormat "%{Referer}i -> %U" referer 210LogFormat "%{User-agent}i" agent 211 212# Include of directories ignores editors' and dpkg's backup files, 213# see README.Debian for details. 214 215# Include generic snippets of statements 216IncludeOptional conf-enabled/*.conf 217 218# Include the virtual host configurations: 219IncludeOptional sites-enabled/*.conf 220 221# vim: syntax=apache ts=4 sw=4 sts=4 sr noet 222 223ScriptAlias /cgi-bin/ "/var/www/cgi-bin/test.cgi" #←ここから下を追記しています 224 225<Directory "/var/www/cgi-bin/"> 226 AllowOverride None 227 Options ExecCGI 228 Order allow,deny 229 Allow from all 230</Directory> 231 232AddHandler cgi-script .cgi 233

経緯3:apache2の設定を読み込むためにapache2再起動しました。

経緯4:ここで、IPアドレス/cgi-bin/ にアクセスしたところ、

#! /usr/bin/env python print "Content-type: text/html\n" print "<html><body>hello python page!</body></html>"

と、cgiが実行されなくて、ソースが表示されてしまいます。

###試したこと
IPアドレス/cgi-bin/test.cgiにアクセスしてみましたが、404エラーでした。

どなたか、原因がお分かりになる方、アドバイスなどいただけると大変助かります。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答3

0

cgi_module または cgid_module が有効になっていないのだと思います。

$ sudo /usr/sbin/a2enmod cgid $ ls /etc/apache2/mods-enabled/cgi* /etc/apache2/mods-enabled/cgid.conf /etc/apache2/mods-enabled/cgid.load $ sudo /usr/sbin/service apache2 restart

また、標準では、/etc/apache2/conf-enabled/serve-cgi-bin.conf (../conf-available/serve-cgi-bin.conf へのシンボリックリンク)で ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ が定義されていて、apache2.conf に追加した設定と競合します。
apache2.conf の方を削除するか、または、下記のように serve-cgi-bin.conf を無効にする必要があります。

$ sudo /usr/sbin/a2disconf serv-cgi-bin $ sudo /usr/sbin/service apache2 restart

投稿2016/05/13 15:53

TaichiYanagiya

総合スコア12141

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

bin_300K

2016/05/13 16:11

TaichiYanagiyaさま どうもありがとうございます。仰せのようにコマンドを打ちましたが、相変わらずエラーが出てしまっております。エラーログは以下のようになっております。もし何かわかれば教えていただけると大変助かります。夜分遅くありがとうございました。 「[Sat May 14 01:06:51.355833 2016] [cgi:error] [pid 21505:tid 1953494064] [client (IPアドレス):50311] AH01215: (8)Exec format error: exec of '/home/(ユーザー名)/public_html/cgi-bin/test.py' failed, referer: http://(IPアドレス)/~(ユーザー名)/cgi-bin/ [Sat May 14 01:06:51.358138 2016] [cgi:error] [pid 21505:tid 1953494064] [client (IPアドレス):50311] End of script output before headers: test.py, referer: http://(IPアドレス)/~(ユーザー名)/cgi-bin」 以上の2点のエラーがでてしまいます・・・ほんとに夜分遅くにありがとうございます。
bin_300K

2016/05/14 02:34

経過後報告です。 その後アドバイスを踏まえ色々試行錯誤した結果、スクリプトの文字コードを見直したところ、おかげさまで、無事CGIが動きました! ご協力、ありがとうございました! となっているのが、問題となるケースもあるようでしたので、with BOMを消して、CRLF改行を消すと、無事実行されました!! ご協力いただきありがとうございました。
guest

0

ログにエラーが出ていませんか?
明らかに、設定ファイルの書き方がおかしいです。

<Directory /var/www/> Require all granted </Directory>

これは、apache2.4の書き方。

<Directory "/var/www/cgi-bin/"> Order allow,deny Allow from all </Directory>

これは、apache2.2以前の書き方です。

お使いのapacheのバージョンはいくつかわかりませんが(まぁ、多分2.4だと思うけど)、どのバージョンでも一緒に書くとエラーになると思います。
バージョンに合わせて書きなおしてください。

CGIのソースが表示される、というのが一番の謎だったのだけど、おそらくブラウザのキャッシュが残って表示されているんじゃないですかね。

(追記)
最初「起動しなくなる」と書きましたが、ちょっと怪しいので消しました。
でも、確認はしたほうがいいと思います。

投稿2016/05/13 11:41

編集2016/05/13 11:52
katsuko

総合スコア3462

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

bin_300K

2016/05/13 13:31

katsukoさま アドバイスありがとうございます。まだはまっていますが、参考にさせていただきます! 取り急ぎ お礼まで
guest

0

ベストアンサー

デフォルトではpythonを実行することはできないと思います。

  • Pythonスクリプトを実行するためにCGIの設定を行う
  • test.cgiではなくtest.pyにファイル名を変更

こちらが参考にして設定されてはいかがでしょうか。
http://qiita.com/aryoa/items/2c28b466e911a3dd101d

投稿2016/05/13 11:24

lightson

総合スコア553

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

bin_300K

2016/05/13 13:30

lightson さま ありがとうございます!今いただいた参考サイトで試しておりますが、まだはまっております。写し間違えなどないかチェックして進めようと思います。 取り急ぎ お礼まで
bin_300K

2016/05/13 15:22

lichtsonさま  先ほどはアドバイスいただきありがとうございました。 経過ご報告いたします。いただいたリンク先のチュートリアル通りに、apache2を3回ほどインストールからやりなおしたのですが、うまくいっておりません。。。すみません。 http://(IPアドレス)/~(ユーザー名)/cgi-bin/test.pyにアクセスすると、 タブ:「500 Internal Server Error」 本文:「Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Apache/2.4.10 (Raspbian) Server at (私のラズパイのIPアドレス) Port 80」 とでてしまいます。 http://(IPアドレス)/~(ユーザー名)/cgi-bin/のディレクトリにアクセスすると、test.pyがこのディレクトリにあります という表示がでますし、 http://(IPアドレス)/~(ユーザー名)/index.html (ディレクトリにテストhtmlを配置しています)は、無事に表示されています。 ここから、CGIの設定の直前まではうまくいっているように思われますが、なにか良いお知恵はございますでしょうか。すみません。
bin_300K

2016/05/13 15:49

追記 状況を詳細に記述するため、別途質問を投稿いたしました。 https://teratail.com/questions/34880 もしご都合よろしければアドバイスいただけると大変助かります。
bin_300K

2016/05/14 02:32

経過後報告です。 文字コードを見直したところ、おかげさまで、無事CGIが動きました! ご協力、ありがとうございました! $ file test.py test.py: Python script, UTF-8 Unicode (with BOM) text executable, with CRLF line terminators となっているのが、問題となるケースもあるようでしたので、with BOMを消して、CRLF改行を消すと、無事実行されました!! ご協力いただきありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問