1. 程式人生 > >Apache-通過CGI執行腳本

Apache-通過CGI執行腳本

.sh round query 執行命令 got www. rect 按鈕 XML

1.配置服務器,開啟註釋

vim /etc/httpd/conf/httpd.conf

292 # (You will also need to add "ExecCGI" to the "Options" directive.)
293 #
294 AddHandler cgi-script .cgi .py .sh
295
296 # For type maps (negotiated resources):
297 #AddHandler type-map var

告訴服務器cgi和pl後綴的文件都是cgi腳本

編寫python腳本,並放入/var/www/cgi-bin/目錄下

#!/usr/bin/python
# -*- coding: utf-8 -*-
print Content-type: text/plain

print Hello, world!

瀏覽器輸入: www.localhost.com/cgi-bin/wang.py

編寫shell腳本,並放入/var/www/cgi-bin/目錄下

#!/bin/sh

echo -e "Content-type: text/plain\n"

echo "hello world!"

瀏覽器輸入: www.localhost.com/cgi-bin/wang.sh

這樣直接通過URL對用戶不友好,但給前端提供了接口,於是我又寫了個html文件,放在www/html文件夾中,名為test.html

服務器通常會有一個www/cgi-bin的目錄,我在這裏放一個shell腳本,名為test2

#!/bin/sh
alias urldecode=sed "s@+@ @g;s@%@\\\\x@g" | xargs -0 printf "%b"
echo -e "Content-type: text/plain\n"
decoded_str=`echo $QUERY_STRING | urldecode`
echo `$decoded_str`

一共就5句:

第1句表示是shell腳本,實際上不加也可以,因為shell是默認的腳本。

第2句我網上抄的,具體原理也不懂,作用是解碼URL, 當URL中有空格時,從客戶端傳過來會變成%20, 20是空格的16進制ASCII碼。

第3句是必須的,否則在客戶端調用時就出錯,是http協議規定的。

第4句就是將URL解碼

第5句是執行命令並返回給客戶端

然後在瀏覽器中輸入URL:127.0.0.1/cgi-bin/test2?pwd

結果為 /var/www/cgi-bin

<html>
<head>
<script>
function httpGet(url)
{
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", url, false); // false: wait respond
        xmlHttp.send(null);
        return xmlHttp.responseText;
}
function f()
{
        var url = "http://127.0.0.1/cgi-bin/test2?" 
           + document.getElementById(in).value;
        document.getElementById(out).innerHTML = httpGet(url);
}
</script>
</head>
<body>
<span>command </span><input id=‘in‘></input>
<button onclick=‘f()‘>send</button>
<br/>
<pre id=‘out‘></pre>
</body>
</html>

兩個js函數,httpGet是網上抄的,f是點擊按鈕的回調函數,主要兩句,第1句獲取用戶輸入並加上前綴組成url,第2句調用httpGet函數並將返回輸出。
使用時,瀏覽器中輸入127.0.0.1/test.html,效果如圖

Apache-通過CGI執行腳本