我获得了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()然而,当我使用http://localhost:8000/test.py执行脚本并试图通过CGI在同一个目录中运行测试脚本时,我看到的是脚本的文本,而不是执行的结果。
权限都是正确设置的,测试脚本本身也不是问题(因为当脚本驻留在cgi-bin中时,我可以使用python -m CGIHTTPServer很好地运行它)。我怀疑这个问题与默认的CGI目录有关。
如何让脚本执行?
发布于 2013-07-12 15:05:45
我的怀疑是正确的。派生此代码的示例显示了将默认目录设置为服务器脚本所在的同一目录的错误方法。若要以这种方式设置默认目录,请使用:
handler.cgi_directories = ["/"]警告:如果您不在任何类型的防火墙后面,这会打开潜在的巨大安全漏洞。这只是一个有教育意义的例子。只需非常小心地使用.
发布于 2014-08-18 00:01:40
如果.cgi_directories需要多层子目录(例如['/db/cgi-bin'] ),则解决方案似乎不起作用(至少对我是这样)。对服务器进行子类化和更改is_cgi def似乎有效。下面是我在您的脚本中添加/替换的内容:
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发布于 2016-05-02 18:34:39
下面是如何使服务器上的每个.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()https://stackoverflow.com/questions/17618084
复制相似问题