remote manage VM with Flask web application

We will use waitress as WSGI to serve the Flask web application, to start it with:
waitress-serve –port=8080 main:app
(in our case, we have main.py with app = Flask(name) inside)
Or you can edit main.py, so it can run with waitress directly, only need two changes:
1. add from waitress import serve at beginning
2. update the last line to serve(app, host=’0.0.0.0′, port=8080)
Here is main.py:

from flask import Flask, redirect, render_template, request, session, url_for
import subprocess
app = Flask(__name__)
def api(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
    stderr=subprocess.PIPE, universal_newlines=True)
    stdout, stderr = p.communicate()
    return stdout
@app.route("/", methods = ["POST", "GET"])
def login():
    if request.method == "POST":
        user = request.form["name"]
        return redirect(url_for("success", name=user))
    else:
        return render_template("login.html")
 
@app.route("/success", methods = ["POST", "GET"])
def success():
    ip_addr = request.form.get('ip_addr')
    cmd = request.form.get('name')
    print(cmd)
    full_cmd = "/home/zhuby/sshpass -p my_password ssh " + ip_addr + " -o ConnectTimeout=2 -o StrictHostKeyChecking=no -o LogLevel=Error " + cmd
    print(full_cmd)
    return render_template("success.html", subprocess_output=api(full_cmd))
 
if __name__ == "__main__":
    app.run("0.0.0.0", 8080)

and login.html:

html>
   <body>
      <form action="{{ url_for('success') }}" method="post">
         <p>Enter the external hostname or IP:</p>
         <p><input type = "text" name = "ip_addr" /></p>
         <p>Enter Command:</p>
         <p><input type = "text" name = "name" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
   </body>
</html>

and success.html

<html>
    <body>
        {% block content %}
         <pre>{{ subprocess_output }}</pre>
        {% endblock %}
    </body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *