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,效果如图

 

转载于:https://www.cnblogs.com/LyShark/p/9104111.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值