Peter
Peter

Reputation: 427

Python script in a browser

So I have a functional python script that performs some sysadmin automation tasks. You give it a hostname and it goes off and does it's thing, SSHing to servers and printing messages to the console as it goes. What is a good technical way to incorporate this with browser support rather than running in a terminal? Really, all that would be required would be an input box on a webpage (for the servers hostname) and that could go and run the script directly and then print the stdout to the browser.

Upvotes: 2

Views: 681

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174614

SimpleHTTPServer is okay, but as its name implies, its quite simple. Try a microframework, like Flask which includes a webserver and helpers to make things easier for you. The script couldn't be more simple:

from tools import thingamajig
from flask import Flask, request

app = Flask(__name__)

@app.route('/go-go-gadget', methods=['POST','GET'])
def index():
   if request.method == 'POST':
       ip_address = request.form['ip_address']
       results = thingamajig.do(ip_address)
       return render('index.html', results=results)
   return render('index.html')

if __name__ == '__main__':
   app.run()

Now just create a templates/ directory and in it, add a file index.html with the following:

<form method="POST">
   <input type="text" name="ip_address" />
   <input type="submit">
</form>
{% if results %}
   Here are the results: {{ results }}
{% endif %}

Now just python server.py and go to http://localhost:5000/go-go-gadget

Upvotes: 2

Paulo Bu
Paulo Bu

Reputation: 29794

Actually you won't need too much. You'll need to deploy a web server that executes the script and the script should give the output as an HTTP response rather than writing to STDOUT.

That being said, you can use Python's built in SimpleHTTPServer for starters. It is a very basic web server (which can be improved) already written for you in Python's standard library. I'll rather use this for sysadmin and intranet tasks than Apache because it is very easy to set it up and start serving.

You'll probably need to extend it so when the request to run the script comes, it know what to do with it. SimpleHTTPServer maybe is not a good fit here but you can extend BaseHTTPServer or CGIHTTPServer to accomplish the script execution.

On the script side you'll need to modify the output's target, nothing more clever than that. It'll probably require some refactoring but not much.

Keep in mind that BaseHTTPServer is not focused on security, so use this in safe environments or the data of your company might be compromised.

I can get into any more details because the question is rather big but that is how I would start doing it.

Hope it helps!

Upvotes: 2

Related Questions