Python CGIHTTPServer Default Directories

I have the following minimum code for a CGI processing HTTP server, obtained from several examples on inner pipes:

#!/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() 

However, when I execute the script and try to run the test script in the same directory via CGI using http://localhost:8000/test.py , I see the text of the script, not the results of the execution.

Permissions are set correctly, and the test script itself is not a problem (since I can run it using python -m CGIHTTPServer when the script is in cgi-bin). I suspect the problem has something to do with the default CGI directories.

How can i execute the script?

+4
source share
3 answers

My suspicions were correct. The examples from which this code was obtained showed the wrong way to set the default directory to the same directory as the script server. To set the default directory this way, use:

 handler.cgi_directories = ["/"] 

A warning. This opens up potentially huge security holes if you are not behind any kind of firewall. This is just an instructive example. Use only with extreme caution.

+4
source

The solution does not work (at least for me) if .cgi_directories requires several levels of subdirectories (for example, ['/db/cgi-bin'] ). The server subclass and the change to is_cgi def seemed to work. Here, what I added / replaced in the script:

 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 
+3
source

Here is how you would make each .py file on the server a cgi file (you probably don't want this to be for production / public server;):

 import BaseHTTPServer import CGIHTTPServer import cgitb; cgitb.enable() server = BaseHTTPServer.HTTPServer # Treat everything as a cgi file, ie # `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() 
0
source

Source: https://habr.com/ru/post/1491142/


All Articles