zoukankan      html  css  js  c++  java
  • 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
    "
    
    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
    "
    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,效果如图

  • 相关阅读:
    JavaWeb--HttpSession案例
    codeforces B. Balls Game 解题报告
    hdu 1711 Number Sequence 解题报告
    codeforces B. Online Meeting 解题报告
    ZOJ 3706 Break Standard Weight 解题报告
    codeforces C. Magic Formulas 解题报告
    codeforces B. Sereja and Mirroring 解题报告
    zoj 1109 Language of FatMouse 解题报告
    hdu 1361.Parencodings 解题报告
    hdu 1004 Let the Balloon Rise 解题报告
  • 原文地址:https://www.cnblogs.com/LyShark/p/9104111.html
Copyright © 2011-2022 走看看