Skip to content

Instantly share code, notes, and snippets.

@peycho
Created August 2, 2023 11:48
Show Gist options
  • Save peycho/212b2718e283b69a9c14dd386593c10e to your computer and use it in GitHub Desktop.
Save peycho/212b2718e283b69a9c14dd386593c10e to your computer and use it in GitHub Desktop.
Execute bash script via basic http api
import http.server
import socketserver
import subprocess
PORT = 8000
REQUEST_TIMEOUT = 600
SCRIPT = "/home/ubuntu/test.sh"
class MyHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
self.server.timeout = REQUEST_TIMEOUT
if self.path == '/api':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'200 OK!')
elif self.path == '/run_app':
try:
script_path = SCRIPT
result = subprocess.run(['bash', script_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
if result.returncode == 0:
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(result.stdout.encode())
else:
self.send_response(500)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(result.stderr.encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(str(e).encode())
else:
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'Not found.')
if __name__ == '__main__':
try:
with socketserver.ThreadingTCPServer(('', PORT), MyHandler) as httpd:
httpd.timeout = REQUEST_TIMEOUT
print(f"Server started at port {PORT}")
httpd.serve_forever()
except KeyboardInterrupt:
print("Server stopped.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment