Tomas Vilemaitis Tomas Vilemaitis - 1 month ago 8
Linux Question

Web in python that interacts with linux

Is there a way to make web in python (mixed with

html/php
) that interacts with PC (
linux
OS) ?

As example: you click button in webpage and It sends command to PC (
linux
) that activates another
python
script, but not in web format (example: I push button 'RUN PYTHON.PY SCRIPT' and it sends command to PC to activate it)

web server
will be on the same computer,
localhost

Answer

Yes, it is possible. Here is one way to do it.

#!/usr/bin/env python

import os

from flask import Flask
app = Flask(__name__)

@app.route('/')
def root():
    return '''
        <html><body><form action="/run" method="post">
            <input type="submit" value="Run Python Script!"/>
        </form></body></html>'''

@app.route('/run', methods=['POST'])
def run():
    os.system("python /tmp/script.py > /tmp/out 2>&1")
    return '''<html><body><p>The script has run.</p></body></html>'''

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

Here is an example which passes information from the form to the python script:

#!/usr/bin/env python

import os

from flask import Flask, request
app = Flask(__name__)

@app.route('/')
def root():
    return '''
        <html><body><form action="/run" method="post">
            Arg1: <input name="Arg1"/><br/>
            Arg2: <input name="Arg2"/><br/>
            <input type="submit" value="Run Python Script!"/>
        </form></body></html>'''

@app.route('/run', methods=['POST'])
def run():
    # DANGER! DANGER! Example code only. Code injection bug in next line
    cmd = "python /tmp/script.py {} {} > /tmp/out 2>&1".format(
        request.form.get('Arg1'),
        request.form.get('Arg2'),
    )
    os.system(cmd)
    return '''<html><body><p>The script has run.</p></body></html>'''

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

In each of these examples, you'll want to consider the security requirements of your own application. I have highlighted one security vulnerability in the second example; there may be others.

Comments