def do_POST(self):
deploy_steps_match = re.match(
r'/v1/nodes/([^/]*)/vendor_passthru/deploy_steps', self.path)
callback_match = re.search(
r'/v1/nodes/([^/]*)/vendor_passthru', self.path)
if deploy_steps_match is not None:
tmp = tempfile.NamedTemporaryFile()
json.dump({'url': None}, tmp)
tmp.flush()
self.path = tmp.name
elif callback_match is not None:
callback_file_path = os.path.join(
CONF.ramdisk_func_test_workdir, callback_match.group(1),
'callback')
open(callback_file_path, 'a').close()
LOG.info("Got callback: %s", self.path)
self.path = os.path.join(self.ctx.htdocs, 'stubfile')
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
python类SimpleHTTPRequestHandler()的实例源码
def do_GET(self):
if self.path == '/':
# Create the response
response = {
'billing_id': config_custom.billing_id,
'customer_id' : config_custom.customer_id,
'location_id' : config_custom.location_id,
}
# Optionally include other information
if config_custom.is_note_displayed:
response['note_text'] = config_custom.note_text
# Write the response
self.protocol_version = 'HTTP/1.1'
self.send_response(200, 'OK')
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(json.dumps(response)))
# self.path = '/'
return
# return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def basicWebServer(self):
import SimpleHTTPServer
import SocketServer
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
while (True):
try:
print "Trying to open on port", PORT
httpd = SocketServer.TCPServer(("", PORT), Handler)
except Exception as e:
print "port", PORT, "did not work, checking next port"
PORT += 1
else:
break
print "serving at port", PORT
webbrowser.open("http://localhost:"+str(PORT)+"/forceD3/force.html")
httpd.serve_forever()
### FUNCTIONS TO BE DEFINED IN SUBCLASSES ###
def __init__(self,request, client_address, server):
self.server = server
self.protocol_version = 'HTTP/1.1'
self.challengeMessage = None
self.target = None
self.client = None
self.machineAccount = None
self.machineHashes = None
self.domainIp = None
global ATTACKED_HOSTS
if self.server.target in ATTACKED_HOSTS and self.server.one_shot:
logging.info(
"HTTPD: Received connection from %s, skipping %s, already attacked" % (
client_address[0], self.server.target))
return
if self.server.target is not None:
logging.info(
"HTTPD: Received connection from %s, attacking target %s" % (client_address[0], self.server.target))
else:
logging.info(
"HTTPD: Received connection from %s, attacking target %s" % (client_address[0], client_address[0]))
SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self,request, client_address, server)
def __init__(self,request, client_address, server):
self.server = server
self.protocol_version = 'HTTP/1.1'
self.challengeMessage = None
self.target = None
self.client = None
self.machineAccount = None
self.machineHashes = None
self.domainIp = None
self.authUser = None
if self.server.config.mode != 'REDIRECT':
if self.server.config.target is not None:
self.target = self.server.config.target.get_target(client_address[0],self.server.config.randomtargets)
logging.info("HTTPD: Received connection from %s, attacking target %s" % (client_address[0] ,self.target[1]))
else:
self.target = self.client_address[0]
logging.info("HTTPD: Received connection from %s, attacking target %s" % (client_address[0] ,client_address[0]))
SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self,request, client_address, server)
def main():
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
Handler.extensions_map['.pac'] = 'application/x-ns-proxy-autoconfig'
try:
port = int(sys.argv[1])
except:
port = DEFAULT_PORT
print "Serving at port %s/tcp ..." % port
httpd = SocketServer.TCPServer(("", port), Handler)
httpd.serve_forever()
##############
# Enry Point #
##############
def server_server():
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
try:
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
except Exception:
pass
print 'already serving'
# makes start block from template using
def server_server():
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
try:
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
except Exception:
pass
print 'already serving'
# makes start block from template using
def setUpClass(cls):
"""
Set up an HTTP server to serve the XML files. Set the correct port in
the IGD.xml URLBase element.
"""
# Have to chdir here because the py2 SimpleHTTPServer doesn't allow us
# to change its working directory like the py3 one does.
os.chdir(path.join(path.dirname(path.realpath(__file__)), 'xml'))
cls.httpd = sockserver.TCPServer(('127.0.0.1', 0), httpserver.SimpleHTTPRequestHandler)
cls.httpd_thread = threading.Thread(target=cls.httpd.serve_forever)
cls.httpd_thread.daemon = True
cls.httpd_thread.start()
cls.httpd_port = cls.httpd.server_address[1]
with open('upnp/IGD.xml', 'w') as out_f:
with open('upnp/IGD.xml.templ') as in_f:
out_f.write(in_f.read().format(port=cls.httpd_port))
def main():
logging.info('pyhttps {}'.format(version))
create_ssl_cert()
atexit.register(exit_handler)
if PY3:
import http.server
import socketserver
import ssl
logging.info('Server running... https://{}:{}'.format(server_host, server_port))
httpd = socketserver.TCPServer((server_host, server_port), http.server.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile=ssl_cert_path, server_side=True)
else:
import BaseHTTPServer
import SimpleHTTPServer
import ssl
logging.info('Server running... https://{}:{}'.format(server_host, server_port))
httpd = BaseHTTPServer.HTTPServer((server_host, server_port), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile=ssl_cert_path, server_side=True)
httpd.serve_forever()
def run_action(self):
current_cwd = os.getcwd()
self.ui.print_msg("Starting web server on port %s" % self.vars["port"][0])
print "\033[33m"
try:
httpd = BaseHTTPServer.HTTPServer(('0.0.0.0', int(self.vars["port"][0])), SimpleHTTPServer.SimpleHTTPRequestHandler)
if self.vars["https"][0].lower() == "true":
httpd.socket = ssl.wrap_socket(httpd.socket, certfile=self.vars["certificate"][0], server_side=True)
os.chdir(self.vars["folder"][0])
httpd.serve_forever()
except KeyboardInterrupt:
print "\033[00m"
self.ui.print_msg("Stopping web server")
except:
print "\033[00m"
self.ui.print_error("The web server raised an exception")
os.chdir(current_cwd)
def __init__(self,request, client_address, server):
self.server = server
self.protocol_version = 'HTTP/1.1'
self.challengeMessage = None
self.target = None
self.client = None
self.machineAccount = None
self.machineHashes = None
self.domainIp = None
self.authUser = None
if self.server.config.mode != 'REDIRECT':
if self.server.config.target is not None:
self.target = self.server.config.target.get_target(client_address[0],self.server.config.randomtargets)
logging.info("HTTPD: Received connection from %s, attacking target %s" % (client_address[0] ,self.target[1]))
else:
self.target = self.client_address[0]
logging.info("HTTPD: Received connection from %s, attacking target %s" % (client_address[0] ,client_address[0]))
SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self,request, client_address, server)
def run(self, open_immediately, port):
'''
Serves the `www` directory.
Args:
open_immediately: Whether to open the web browser immediately
port: The port at which to serve the graph
'''
os.chdir(self.directory)
handler = http.SimpleHTTPRequestHandler
handler.extensions_map.update({
'.webapp': 'application/x-web-app-manifest+json',
})
server = socketserver.TCPServer(('', port), handler)
server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
address = 'http://localhost:{0}/graph.html'.format(port)
log.info('Serving at %s', address)
if open_immediately:
log.debug('Opening webbrowser')
webbrowser.open(address)
server.serve_forever()
def do_GET(self):
matches = re.match(PATH_REGEX, self.path)
if matches:
path = matches.group(1)
elif self.path == '/web/' and self.server.apiGatewayClientUrl != None:
f = open("web/index.html")
html = f.read()
f.close()
html = html.replace('src="apiGateway-js-sdk/','src="'+self.server.apiGatewayClientUrl+'/apiGateway-js-sdk/')
self.respond(200,html)
return
else:
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
#return super(MyHandler,self).do_GET()
#self.respond(404, "Not Found")
#return
try:
page = self.server.serverIface.getPage('<httpserver>', path)
self.respond(200, page["html"])
except custom_exceptions.NotFound:
self.respond(404, "Not Found")
except:
self.respond(500, "Internal Error")
def send_head(self):
"""Version of send_head that support CGI scripts"""
if self.is_cgi():
return self.run_cgi()
else:
return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)
def do_GET(self):
if self.is_tryton_url(self.path):
self.send_tryton_url(self.path)
return
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def do_HEAD(self):
if self.is_tryton_url(self.path):
self.send_tryton_url(self.path)
return
SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD(self)
def send_head(self):
"""Version of send_head that support CGI scripts"""
if self.is_cgi():
return self.run_cgi()
else:
return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)
def __init__(self, ctx, *args, **kwargs):
self.ctx = ctx
SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(
self, *args, **kwargs)
def do_GET(self):
LOG.info('Got GET request: %s', self.path)
fake_check = re.match(r'/fake', self.path)
tenant_images_match = re.match(r'/tenant_images/(.*)$', self.path)
deploy_steps_match = re.match(
r'/v1/nodes/([^/]*)/vendor_passthru/deploy_steps', self.path)
if fake_check is not None:
LOG.info("This is 'fake' request.")
self.path = os.path.join(self.ctx.htdocs, 'stubfile')
elif tenant_images_match is not None:
LOG.info("This is 'tenant-images' request: %s", self.path)
tenant_image = tenant_images_match.group(1)
self.path = os.path.join(self.ctx.images_path, tenant_image)
elif deploy_steps_match is not None:
with open('{}.pub'.format(self.ctx.ssh_key)) as data:
ssh_key = data.read().rstrip()
data = {
'name': 'inject-ssh-keys',
'payload': {
'ssh-keys': {
'root': [ssh_key]
}
}
}
tmp = tempfile.NamedTemporaryFile()
json.dump(data, tmp)
tmp.flush()
self.path = tmp.name
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def do_GET(self):
path = self.path.lstrip('/').split('?')[0]
print("GET: ", path)
# is the file in the redirects table?
if path in self.redirects:
path_to = self.redirects[path]
print("REDIRECT TO ", path_to)
self.send_response(301)
self.send_header('location', path_to)
self.end_headers()
return True
else:
# serve the file!
self.path = path
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def handle_one_request(self):
try:
SimpleHTTPServer.SimpleHTTPRequestHandler.handle_one_request(self)
except:
pass
def handle_one_request(self):
try:
SimpleHTTPServer.SimpleHTTPRequestHandler.handle_one_request(self)
except KeyboardInterrupt:
raise
except Exception, e:
logging.error('Exception in HTTP request handler: %s' % e)
def do_POST(self):
post_request = []
printt(3, "%s - sent POST request." %self.address_string())
form = cgi.FieldStorage(self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],})
try:
from core.shell import url
logger = open("%s.log" %url.replace("https://", "").replace("http://", "").split("/")[0], "a")
logger.write("\n## %s - Data for %s\n\n" %(time.strftime("%H:%M:%S - %d/%m/%y"), url))
for tag in form.list:
tmp = str(tag).split("(")[1]
key,value = tmp.replace(")", "").replace("\'", "").replace(",", "").split()
post_request.append("%s %s" %(key,value))
printt(2, "%s => %s" %(key,value))
logger.write("%s => %s\n" %(key,value))
logger.close()
from core.shell import action_url
create_post(url,action_url, post_request)
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
except socerr as e:
printt(3, "%s igonring ..." %str(e))
except Exception as e:
printt(3, "%s igonring ..." %str(e))
def serve(port=PORT):
'''Serves test XML files over HTTP'''
# Make sure we serve from the tests' XML directory
os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)),
'xml'))
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
class TestServer(SocketServer.TCPServer):
allow_reuse_address = True
httpd = TestServer(("", PORT), Handler)
print 'Serving test HTTP server at port', PORT
httpd_thread = Thread(target=httpd.serve_forever)
httpd_thread.setDaemon(True)
httpd_thread.start()
def test_simple_HTTP(self) :
# ============== Setting up an HTTP server at 'http://localhost:8001/' in current directory
try :
PORT = int(sys.argv[1])
except :
PORT = randint(1025, 65535)
try :
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
except :
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
print ("Serving at port %d" % PORT)
http_thread = Thread( target = httpd.serve_forever, )
http_thread.daemon = True
# ============== Starting the HTTP server
http_thread.start()
# ============== Wait until HTTP server is ready
sleep(1)
with remote_repo(['test_package'], base_url = 'http://localhost:%d/' % PORT) :
from test_package import module1
self.assertTrue(module1.dummy_str) # If this point is reached then the module1 is imported succesfully!
def setUp(self):
super(WebSocketRequestHandlerTestCase, self).setUp()
self.stubs = stubout.StubOutForTesting()
self.tmpdir = tempfile.mkdtemp('-websockify-tests')
# Mock this out cause it screws tests up
self.stubs.Set(os, 'chdir', lambda *args, **kwargs: None)
self.stubs.Set(SimpleHTTPRequestHandler, 'send_response',
lambda *args, **kwargs: None)
def test_normal_get_with_only_upgrade_returns_error(self):
server = self._get_server(web=None)
handler = websocket.WebSocketRequestHandler(
FakeSocket('GET /tmp.txt HTTP/1.1'), '127.0.0.1', server)
def fake_send_response(self, code, message=None):
self.last_code = code
self.stubs.Set(SimpleHTTPRequestHandler, 'send_response',
fake_send_response)
handler.do_GET()
self.assertEqual(handler.last_code, 405)
def test_list_dir_with_file_only_returns_error(self):
server = self._get_server(file_only=True)
handler = websocket.WebSocketRequestHandler(
FakeSocket('GET / HTTP/1.1'), '127.0.0.1', server)
def fake_send_response(self, code, message=None):
self.last_code = code
self.stubs.Set(SimpleHTTPRequestHandler, 'send_response',
fake_send_response)
handler.path = '/'
handler.do_GET()
self.assertEqual(handler.last_code, 404)
def send_head(self):
"""Version of send_head that support CGI scripts"""
if self.is_cgi():
return self.run_cgi()
else:
return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)