Apache 通过CGI执行脚本

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

posted @   lyshark  阅读(1287)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

8951350 | 6896840
博客园 - 开发者的网上家园

点击右上角即可分享
微信分享提示