Skip to content

Instantly share code, notes, and snippets.

@davidmroth
Created May 17, 2021 06:11
Show Gist options
  • Select an option

  • Save davidmroth/1b55aa812d6894dfee2a0d49c3e16f82 to your computer and use it in GitHub Desktop.

Select an option

Save davidmroth/1b55aa812d6894dfee2a0d49c3e16f82 to your computer and use it in GitHub Desktop.
Linux Dash Python Script and Systemd Startup
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer, test as _test
import subprocess
from SocketServer import ThreadingMixIn
import argparse
import base64
import ssl
import logging
import logging.handlers
logger = logging.getLogger('Linux Dash')
logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
logger.addHandler(handler)
parser = argparse.ArgumentParser(description='Simple Threaded HTTP server to run linux-dash.')
parser.add_argument('--port', metavar='PORT', type=int, nargs='?', default=80,
help='Port to run the server on.')
parser.add_argument('--password', metavar='PASSWORD', type=str, nargs='?', default="",
help='Password to protect access.')
parser.add_argument('--use_ssl', default=False, action='store_true',
help='Use SSL.')
modulesSubPath = '/server/linux_json_api.sh'
appRootPath = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
pass
class MainHandler(BaseHTTPRequestHandler):
def do_AUTHHEAD(self):
self.send_response(401)
self.send_header('WWW-Authenticate', 'Basic realm=\"AUTH\"')
self.send_header('Content-type', 'text/html')
self.end_headers()
return
def do_GET(self):
global key
try:
''' Present frontpage with user authentication. '''
if key and self.headers.getheader('Authorization') == None:
self.do_AUTHHEAD()
self.wfile.write('!! UNAUTHORIZED !!')
self.wfile.write(key)
elif not key or self.headers.getheader('Authorization') == 'Basic '+key:
data = ''
contentType = 'text/html'
if self.path.startswith("/server/"):
module = self.path.split('=')[1]
output = subprocess.Popen(
appRootPath + modulesSubPath + " " + module,
shell = True,
stdout = subprocess.PIPE)
data = output.communicate()[0]
else:
if self.path == '/':
self.path = 'index.html'
f = open(appRootPath + os.sep + self.path)
data = f.read()
if self.path.startswith('/linuxDash.min.css'):
contentType = 'text/css'
f.close()
self.send_response(200)
self.send_header('Content-type', contentType)
self.end_headers()
self.wfile.write(data)
else:
self.do_AUTHHEAD()
self.wfile.write(self.headers.getheader('Authorization'))
self.wfile.write('not authenticated')
except IOError:
self.send_error(404, 'File Not Found: %s' % self.path)
return
if __name__ == '__main__':
args = parser.parse_args()
key = base64.b64encode(args.password)
logger.debug("Linux Dash 'User:Pasword' is: {} (base64 encoded)".format(key))
server = ThreadedHTTPServer(('0.0.0.0', args.port), MainHandler)
if args.use_ssl:
server.socket = ssl.wrap_socket(server.socket,
keyfile='/etc/swallowtherapy.com/server.key',
certfile='/etc/swallowtherapy.com/fullchain.crt',
server_side=True)
print('Starting server, use <Ctrl-C> to stop')
try:
server.serve_forever()
except KeyboardInterrupt:
pass
server.server_close()
# Then put this file at: /etc/systemd/system/linux-dash.service
#
# To start linux-dash and check that it's running:
# > sudo systemctl start linux-dash.service
# > sudo systemctl status linux-dash.service
# To enable linux-dash for automatic start up:
# > sudo systemctl enable linux-dash.service
# Don't forget to change the username:password below
[Unit]
Description=Linux Dash
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/python /home/ampcare/linux-dash-master/app/server/index.py --port 8090 --password "admin:admin" --use_ssl
TimeoutStopSec=20
KillMode=process
Restart=on-failure
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment