天天看点

apache2 启用 CGI,使用 Python 编写 CGI 脚本

文章目录

  • ​​系统环境​​
  • ​​安装 apache2​​
  • ​​使能 CGI​​
  • ​​重启​​
  • ​​编写脚本​​
  • ​​测试脚本​​
  • ​​浏览器打开​​
  • ​​更全面的测试脚本​​
  • ​​查看日志文件​​

系统环境

Ubuntu 16.04

安装 apache2

sudo apt update # 更新一下软件列表,否则部分软件包获取失败
sudo apt install apache2      

使能 CGI

cd /etc/apache2/mods-enabled
sudo ln -s ../mods-available/cgi.load cgi.load      

重启

使能 CGI 后,必须重启 apache2

sudo apache2ctl restart      

编写脚本

cd /usr/lib/cgi-bin # 默认的存储位置
sudo touch test
sudo chmod +x test # 必须要有可执行权限
sudo mousepad test # 用你喜爱的编辑器打开编写内容      

测试脚本

分割行不要漏了。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

print # 此处一定要输出一个空行,使用这行空行分割额外的响应头和内容
print "Yes, it's work"      

浏览器打开

firefox http://localhost/cgi-bin/test      

更全面的测试脚本

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

print "Content-type:text/html" # 额外的响应头
print # 响应头和内容分割行
print '<html>' # 以下是页面内容
print '<head>'
print '<title>Hello</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'      

查看日志文件

tail -n 20 /var/log/apache2/error.log # 查看最后 20 条错误记录
tail -n 20 /var/log/apache2/access.log # 查看最后 20 条访问记录