Anti-Commander
Anti-Commander

Reputation: 45

python send commands to interpreter from script and get result

My goal is to create a webpage the uses python and flask. I would like to have the ability to enter some commands into this web page, submit them to flask which will execute the commands in a python interpreter. Flask will then retrieve the results and send them back to the web page for presentation.

How can this be done? I currently am able to execute unix shell commands but cannot for the life of me figure out how to send commands to a python interpreter and retrieve the results.

I guess I should have clarified the purpose. This is for an internal web application for the company that I work for. Only employees will be able to access it while on our network and only after proper authentication has been performed. The employees need a way to have an interactive shell with the particular machine that they are logged in to through their web browser.

SOLUTION:

I found a nice module name Pexpect that does exactly what I want. Thank you for all of your suggestions.

Upvotes: 0

Views: 1339

Answers (3)

anubhav maity
anubhav maity

Reputation: 71

The following code uses flask and pexpect module to call python interpreter.

@app.route('/console')
def console(): 
    import pexpect
    child = pexpect.spawn('python')
    child.expect('\n>>>')
    child.sendline('import os')
    child.expect('\n>>>')

Upvotes: 1

Miguel Grinberg
Miguel Grinberg

Reputation: 67492

The Werkzeug debugger that is included with Flask can do this when there is an exception, so I think it should be fairly easy to base your solution on that code, or at least to learn how Werkzeug does it.

The debugger server side code is here. The client side is here.

I hope you have a good reason to do this, you normally do not want random people to execute code on your server.

Upvotes: 0

Steve Allison
Steve Allison

Reputation: 1111

Well, you can invoke python in the same way as you do a shell script and pass python code to it using the -c option. See http://docs.python.org/2/using/cmdline.html

However, this is unbelievably insecure and I would not recommend doing it in a web app!

If you are set on this, read up on restricted execution in Python http://docs.python.org/2/library/restricted.html

Upvotes: 0

Related Questions