Skip to content

Instantly share code, notes, and snippets.

@ff6347
Forked from ljack/server.py
Created October 6, 2021 08:01
Show Gist options
  • Save ff6347/02a9adb8d8ccd278f7421c0193660f75 to your computer and use it in GitHub Desktop.
Save ff6347/02a9adb8d8ccd278f7421c0193660f75 to your computer and use it in GitHub Desktop.
python 3 http server with tail file
from os import listdir,SEEK_END
from os.path import isfile, join, getmtime
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
import time
import subprocess
import select
from urllib.parse import parse_qs,urlparse
import logging
import sys, os, socket
from socketserver import ThreadingMixIn
from http.server import SimpleHTTPRequestHandler, HTTPServer
class ThreadingSimpleServer(ThreadingMixIn, HTTPServer):
pass
PORT=8080
mypath = "./"
logging.basicConfig(filename='server.log',level=logging.DEBUG)
logging.info("Logging setup done")
def follow(thefile):
## get existing lines
for line in thefile:
yield line
## follow the remaining lines
thefile.seek(0, SEEK_END)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line
def listfiles(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
print (onlyfiles)
self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>", "utf-8"))
self.wfile.write(bytes("<body><p>This is a test.</p>", "utf-8"))
for f in onlyfiles:
l = "<p><a href=\"tail?fname="+f+"\">"+f+"</a>"+str(getmtime(mypath+f))
l += "</p>"
self.wfile.write(bytes(l, "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
def get_query_field(url, field):
try:
return parse_qs(urlparse(url).query)[field]
except KeyError:
return []
def tail(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
fname =get_query_field(self.path, "fname")[0]
# urllib.parse.parse_qs(urllib.parse.parse_qs(self.path).query).get('fname', None)
logging.debug (fname)
file = mypath+fname
logging.debug (file)
logfile = open(file,"r")
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
logging.debug (onlyfiles)
self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>", "utf-8"))
self.wfile.write(bytes("<body><p>This is a test.</p>", "utf-8"))
loglines = follow(logfile)
for line in loglines:
self.wfile.write(bytes(line, "utf-8"))
self.wfile.write(bytes("<br/>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
class RequestsHandler(BaseHTTPRequestHandler):
cgi_directories = ["/www"] #to run all scripts in '/www' folder
def do_GET(self):
logging.info (self.path)
try:
if self.path == '/ls':
listfiles(self)
elif self.path.startswith('/tail'):
tail(self)
except IOError:
self.send_error(404, "Page '%s' not found" % self.path)
def main():
logging.info("Starting..")
with ThreadingSimpleServer(("localhost", PORT), RequestsHandler) as server:
server.serve_forever()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment