1

I'm trying to run a subprocess from a Flask route, but I get a 500 error. It works when I run it directly from the shell. Why isn't it working?

import subprocess
from flask import Flask
app = Flask(__name__)

@app.route('/status/<vmid>')
def status(vmid):
    cmd = "/usr/bin/virsh list --all | grep kvm%s | awk {'print $3'}" % vmid
    p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    out,err = p.communicate()
    return out

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

It raises a 500 error when run through Flask:

root@nc2-kvm:~# python status.py
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
(500 error)

It works when run directly in the shell:

root@nc2-kvm:~# virsh list --all | grep kvm180 | awk {'print $3'}
running
davidism
  • 121,510
  • 29
  • 395
  • 339
  • 1
    is that because you haven't `return` any http response from that view? – Anzel Jul 07 '15 at 15:03
  • In the final code, I've made some changes like set int(vmid), locked it down to the IP of the main server and added a key check to it before executing any command :) – Arjit Chaudhary Jul 09 '15 at 18:36

1 Answers1

0

Take a look at

https://docs.python.org/2/library/subprocess.html

for subprocess.call to work in the form you're using, you would need to set the shell argument to True. To make sure it works, just try your subprocess.call in the python REPL first.

pvg
  • 2,673
  • 4
  • 17
  • 31
  • 1
    @ArjitChaudhary: don't use `shell=True`. Your code as written allows anybody on the internet to run any command on your machine as `root`. – jfs Jul 07 '15 at 19:06
  • 1
    @pvg: don't recommend dangerous solutions without a bit fat disclaimer. Or (better) suggests a safer option such as rewriting `grep`, `awk` parts in Python or [emulating the pipeline using `plumbum`](http://stackoverflow.com/a/16709666/4279). – jfs Jul 07 '15 at 19:09
  • 1
    @J.F.Sebastian the linked documentation contains the disclaimer in red banners, repeatedly. The question is asking about an inherently dangerous code/implementation, presumably for some internal tool. It seemed answering the question is more useful than berating the person asking. – pvg Jul 07 '15 at 19:12
  • In the final code, I've made some changes like set int(vmid), locked it down to the IP of the main server and added a key check to it before executing any command :) – Arjit Chaudhary Jul 07 '15 at 20:25
  • Here's the final code if interested, https://github.com/arjitc/virsh-remote-getstatus/ – Arjit Chaudhary Jul 07 '15 at 20:41