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
扫描二维码关注公众号,回复:
1087260 查看本文章
这样直接通过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`
<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,效果如图