本文整理匯總了Python中http.server方法的典型用法代碼示例。如果您正苦於以下問題:Python http.server方法的具體用法?Python http.server怎麽用?Python http.server使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類http
的用法示例。
在下文中一共展示了http.server方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: run_feed_server
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def run_feed_server():
#stands up the feed server, points to the CB/json_feeds dir
chdir('data/json_feeds/')
port = 8000
handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", port), handler)
try:
print((Fore.GREEN + '\n[+]' + Fore.RESET), end=' ')
print(('Feed Server listening at http://%s:8000' % gethostname()))
httpd.serve_forever()
except:
print((Fore.RED + '\n[-]' + Fore.RESET), end=' ')
print("Server exited")
return
示例2: testInvalidServer
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def testInvalidServer(self):
"""Test download on non-existent server"""
spec = { 'url' : "https://127.1.2.3:7257" }
archive = SimpleHttpArchive(spec, None)
archive.wantDownload(True)
archive.wantUpload(True)
# Local
run(archive.downloadPackage(DummyStep(), b'\x00'*20, "unused", "unused"))
self.assertEqual(run(archive.downloadLocalLiveBuildId(DummyStep(), b'\x00'*20)), None)
# Jenkins
with TemporaryDirectory() as workspace:
with open(os.path.join(workspace, "test.buildid"), "wb") as f:
f.write(b'\x00'*20)
script = archive.download(DummyStep(), "test.buildid", "result.tgz")
callJenkinsScript(script, workspace)
示例3: __init__
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def __init__(self, module, context, logger, srv_host, port, server_type='https'):
try:
threading.Thread.__init__(self)
self.server = http.server.HTTPServer((srv_host, int(port)), RequestHandler)
self.server.hosts = []
self.server.module = module
self.server.context = context
self.server.log = CMEAdapter(extra={'module': self.server.module.name.upper()})
self.cert_path = os.path.join(os.path.expanduser('~/.cme'), 'cme.pem')
self.server.track_host = self.track_host
logging.debug('CME server type: ' + server_type)
if server_type == 'https':
self.server.socket = ssl.wrap_socket(self.server.socket, certfile=self.cert_path, server_side=True)
except Exception as e:
errno, message = e.args
if errno == 98 and message == 'Address already in use':
logger.error('Error starting HTTP(S) server: the port is already in use, try specifying a diffrent port using --server-port')
else:
logger.error('Error starting HTTP(S) server: {}'.format(message))
sys.exit(1)
示例4: shutdown
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def shutdown(self):
try:
while len(self.server.hosts) > 0:
self.server.log.info('Waiting on {} host(s)'.format(highlight(len(self.server.hosts))))
sleep(15)
except KeyboardInterrupt:
pass
# shut down the server/socket
self.server.shutdown()
self.server.socket.close()
self.server.server_close()
# make sure all the threads are killed
for thread in threading.enumerate():
if thread.isAlive():
try:
thread._stop()
except:
pass
示例5: start_serving
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def start_serving(self,host="0.0.0.0"):
serve_dir = os.path.join(Settings.path,"core","www",self.name)
f = open( os.path.join(serve_dir,"index.html"),"w")
f.write(self.html)
f.close()
class ReusableTCPServer(socketserver.TCPServer):
allow_reuse_address = True
logging = False
class MyHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=serve_dir, **kwargs)
def log_message(self, format, *args):
if self.server.logging:
http.server.SimpleHTTPRequestHandler.log_message(self, format, *args)
self.httpd = ReusableTCPServer( (host, self.port), MyHandler)
t = thread.start_new_thread(self.httpd.serve_forever, ())
示例6: __init__
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
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
self.wpad = 'function FindProxyForURL(url, host){if ((host == "localhost") || shExpMatch(host, "localhost.*") ||' \
'(host == "127.0.0.1")) return "DIRECT"; if (dnsDomainIs(host, "%s")) return "DIRECT"; ' \
'return "PROXY %s:80; DIRECT";} '
if self.server.config.mode != 'REDIRECT':
if self.server.config.target is None:
# Reflection mode, defaults to SMB at the target, for now
self.server.config.target = TargetsProcessor(singleTarget='SMB://%s:445/' % client_address[0])
self.target = self.server.config.target.getTarget(self.server.config.randomtargets)
LOG.info("HTTPD: Received connection from %s, attacking target %s://%s" % (client_address[0] ,self.target.scheme, self.target.netloc))
try:
http.server.SimpleHTTPRequestHandler.__init__(self,request, client_address, server)
except Exception as e:
LOG.debug("Exception:", exc_info=True)
LOG.error(str(e))
示例7: run
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def run(self):
LOG.info("Setting up HTTP Server")
if self.config.listeningPort:
httpport = self.config.listeningPort
else:
httpport = 80
# changed to read from the interfaceIP set in the configuration
self.server = self.HTTPServer((self.config.interfaceIp, httpport), self.HTTPHandler, self.config)
try:
self.server.serve_forever()
except KeyboardInterrupt:
pass
LOG.info('Shutting down HTTP Server')
self.server.server_close()
示例8: http_server
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def http_server():
"""Spawns a HTTP server in a separate process, serving test fixtures.
Yields base URL of the HTTP server (e.g., http://localhost:1234/)
"""
oldcwd = os.getcwd()
os.chdir(pkg_resources.resource_filename('vulnix', 'tests/fixtures'))
httpd = http.server.HTTPServer(
('localhost', 0), http.server.SimpleHTTPRequestHandler)
port = httpd.server_port
child = os.fork()
if child == 0:
signal.alarm(3600) # safety belt
httpd.serve_forever()
return # never reached
os.chdir(oldcwd)
yield 'http://localhost:{}/'.format(port)
os.kill(child, signal.SIGTERM)
os.wait()
示例9: make_http_drain_method
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def make_http_drain_method(context):
context.http_drain_method = drain_lib.HTTPDrainMethod(
service="fake_service",
instance="fake_instance",
registrations=["fake_nerve_ns"],
drain={
"url_format": "http://localhost:%d/drain"
% context.fake_http_server.server.server_port,
"success_codes": "200",
},
stop_draining={},
is_draining={
"url_format": "http://localhost:%d/is_draining"
% context.fake_http_server.server.server_port,
"success_codes": "200",
},
is_safe_to_kill={},
)
示例10: test_httpd
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def test_httpd(httpd):
'''
Tests that our http server is working as expected, and that two fetches
of the same url return the same payload, proving it can be used to test
deduplication.
'''
payload1 = content2 = None
url = 'http://localhost:%s/site1/file1.txt' % httpd.server_port
with urllib.request.urlopen(url) as response:
assert response.status == 200
payload1 = response.read()
assert payload1
with urllib.request.urlopen(url) as response:
assert response.status == 200
payload2 = response.read()
assert payload2
assert payload1 == payload2
url = 'http://localhost:%s/420' % httpd.server_port
with pytest.raises(urllib.error.HTTPError) as excinfo:
urllib.request.urlopen(url)
assert excinfo.value.getcode() == 420
示例11: test_httpd
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def test_httpd(httpd):
'''
Tests that our http server is working as expected, and that two fetches
of the same url return the same payload, proving it can be used to test
deduplication.
'''
payload1 = content2 = None
url = make_url(httpd, '/site1/file1.txt')
with urllib.request.urlopen(url) as response:
assert response.status == 200
payload1 = response.read()
assert payload1
with urllib.request.urlopen(url) as response:
assert response.status == 200
payload2 = response.read()
assert payload2
assert payload1 == payload2
示例12: spawn_web_server
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def spawn_web_server(build_dir=None):
if build_dir is None:
build_dir = BUILD_PATH
tmp_dir = tempfile.mkdtemp()
log_path = pathlib.Path(tmp_dir) / "http-server.log"
q = multiprocessing.Queue()
p = multiprocessing.Process(target=run_web_server, args=(q, log_path, build_dir))
try:
p.start()
port = q.get()
hostname = "127.0.0.1"
print(
f"Spawning webserver at http://{hostname}:{port} "
f"(see logs in {log_path})"
)
yield hostname, port, log_path
finally:
q.put("TERMINATE")
p.join()
shutil.rmtree(tmp_dir)
示例13: start_server
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def start_server(self, server_ip):
"""
Start local http server
"""
HOST, PORT = "0.0.0.0", 0
global REPO
self.server = ThreadedHTTPServer((HOST, PORT), ThreadedHTTPHandler)
ip, port = self.server.server_address
if not REPO:
REPO = "http://%s:%s/repo" % (server_ip, port)
print(("# Listening on %s:%s" % (ip, port)))
server_thread = threading.Thread(target=self.server.serve_forever)
server_thread.daemon = True
server_thread.start()
print(("# Server running in thread:", server_thread.name))
return port
示例14: __init__
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
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]))
http.server.SimpleHTTPRequestHandler.__init__(self,request, client_address, server)
示例15: process
# 需要導入模塊: import http [as 別名]
# 或者: from http import server [as 別名]
def process(self,txt):
try:
resp=self.parser.parse_text(txt)
except:
self.send_response(500,"Internal server error")
self.end_headers()
self.wfile.write(traceback.format_exc().encode("utf-8"))
self.wfile.flush()
self.close_connection=True
return
self.send_response(200, 'OK')
self.send_header("Content-type", "text/plain; charset=utf-8")
self.end_headers()
self.wfile.write(resp.encode("utf-8"))
self.wfile.flush()
self.close_connection=True