DEV Community

Muthu
Muthu

Posted on • Updated on

Python Flask app to run Shell script from web service

from flask import Flask
from flask import request
import subprocess
import shlex
import urllib.parse
app = Flask(__name__)

@app.route("/run/",methods = ['POST', 'GET'])
def execute():
    command = 'no command'
    print("============")
    command = (request.data).decode("utf-8")
    print(command)
    if request.method == 'POST':
        print('Started executing command')
        command = shlex.split(command)
        process = subprocess.Popen(command, stdout = subprocess.PIPE)
        print("Run successfully")
        output, err = process.communicate()
        return output
    return "not executed"

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

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
thebouv profile image
Anthony Bouvier

Please no one use this code unless you specifically are looking to set up a honeypot to see what havoc can be created. Social experiment maybe?

At best you'll get your machine destroyed by remote commands running with perms of the web server (which could be pretty wide reaching). At worst your machine will become a zombie for use in more nefarious schemes.

I have to ask: what is a legit reason for doing this? Just seems like a really, really bad idea. Borders on negligent to post this as a how-to article with warnings and explanation. Newbies beware please.

Collapse
 
mu profile image
Muthu

Exactly @thebouv this is not secure one and not recommendable code.

But this is just an example. For some reason, while we are building application which runs only behind the VPN and VPC that time we can use it.

Thanks