Python CGIHTTPServer默认目录

6

我有一个最小的代码,用于处理CGI的HTTP服务器,参考了内部网上的多个示例:

#!/usr/bin/env python

import BaseHTTPServer
import CGIHTTPServer
import cgitb;

cgitb.enable()  # Error reporting

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
handler.cgi_directories = [""]

httpd = server(server_address, handler)
httpd.serve_forever()

当我执行脚本并尝试通过CGI在相同目录下运行测试脚本时,使用http://localhost:8000/test.py,我看到的是脚本的文本而不是执行结果。权限已正确设置,测试脚本本身也没有问题(当脚本位于cgi-bin中时,我可以使用python -m CGIHTTPServer很好地运行它)。我怀疑问题与默认的CGI目录有关。如何使脚本执行?

2
谢谢你的回答!这帮助我解决了一个我已经尝试了很久的Python-only服务器问题。值得指出的是,规范的“正确”shebang是“#!/usr/bin/env python” - 我以前也被这个卡住过! - scubbo
1
@scubbo - 很高兴我的困扰能为你提供一些启示。我已按照你的建议更新了shebang。谢谢! - charleslparker
3个回答

6

我的怀疑是正确的。这段代码的示例来源错误地展示了将默认目录设置为与服务器脚本所在目录相同的方法。要以这种方式设置默认目录,请使用:

handler.cgi_directories = ["/"]

注意:如果您不在任何防火墙后面,这将开放潜在的安全漏洞。这只是一个指导性示例,请极度小心使用。


3

如果 .cgi_directories 需要多层子目录 (例如 ['/db/cgi-bin']),则该解决方案对我来说似乎不起作用。通过子类化服务器并更改 is_cgi 函数似乎有效。这是我在您的脚本中添加/替换的内容:

from CGIHTTPServer import _url_collapse_path
class MyCGIHTTPServer(CGIHTTPServer.CGIHTTPRequestHandler):  
  def is_cgi(self):
    collapsed_path = _url_collapse_path(self.path)
    for path in self.cgi_directories:
        if path in collapsed_path:
            dir_sep_index = collapsed_path.rfind(path) + len(path)
            head, tail = collapsed_path[:dir_sep_index], collapsed_path[dir_sep_index + 1:]
            self.cgi_info = head, tail
            return True
    return False

server = BaseHTTPServer.HTTPServer
handler = MyCGIHTTPServer

2
以下是如何将服务器上的每个 .py 文件制作成 cgi 文件(您可能不希望在生产/公共服务器上这样做 ;)):
import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable()

server = BaseHTTPServer.HTTPServer

# Treat everything as a cgi file, i.e.
# `handler.cgi_directories = ["*"]` but that is not defined, so we need
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):  
  def is_cgi(self):
    self.cgi_info = '', self.path[1:]
    return True

httpd = server(("", 9006), Handler)
httpd.serve_forever()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接