spacepaste

  1.  
  2. #/usr/bin/python3
  3. #
  4. #
  5. # Original copied from https://thepacketgeek.com/give-exabgp-an-http-api-with-flask/,
  6. # liberally modified after.
  7. import cgi
  8. import http.server
  9. import socketserver
  10. from sys import stdout,stdin
  11. from syslog import syslog,openlog,LOG_DEBUG
  12. PORT = 9977
  13. class ServerHandler(http.server.SimpleHTTPRequestHandler):
  14. def createResponse(self, command):
  15. """ Send command string back as confirmation """
  16. self.send_response(200)
  17. self.send_header('Content-Type', 'application/text')
  18. self.end_headers()
  19. self.wfile.write(command.encode())
  20. def do_POST(self):
  21. """ Process command from POST and output to STDOUT """
  22. form = cgi.FieldStorage(
  23. fp=self.rfile,
  24. headers=self.headers,
  25. environ={'REQUEST_METHOD':'POST'})
  26. command = form.getvalue('command')
  27. syslog(LOG_DEBUG,'Received: <%s>' % command)
  28. response = self.handle_data(command)
  29. self.createResponse('Success: %s' % response)
  30. def handle_data(self,command):
  31. stdout.write('%s\n' % command)
  32. stdout.flush()
  33. syslog(LOG_DEBUG,'Waiting for response')
  34. response = ''
  35. for line in stdin:
  36. syslog(LOG_DEBUG,'Response: <%s>' % line.rstrip())
  37. response += 'Received line: <%s>' % line
  38. syslog(LOG_DEBUG,'End of response.')
  39. return response
  40. handler = ServerHandler
  41. httpd = socketserver.TCPServer(('', PORT), handler)
  42. stdout.write('serving at port %s\n' % PORT)
  43. stdout.flush()
  44. httpd.serve_forever()
  45.