apache2 启用 CGI,使用 Python 编写 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"

浏览器打开

看到 Yes, it's work 证明一切都 OK 了。

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 条访问记录
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值