我有一个正在运行的Flask应用程序,但想通过URL传递任何命令,并让flask在主机服务器上执行它并返回结果。
例如运行curl localhost:5000/run/"ls -l"
(命令为ls -l
)时->预期结果:
.
..
file1
file2
etc..
到目前为止,我有:
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello World!"
@app.route('/run/<command>')
def run(command):
return 'Run this %s!' % command
if __name__ == "__main__":
app.run(debug = True)
谢谢。
答案 0 :(得分:0)
只需使其起作用:
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello World!"
@app.route('/run/<command>')
def run(command):
out = os.popen(command).read()
return (out)
if __name__ == "__main__":
app.run(debug = True)
答案 1 :(得分:0)
我建议在JSON请求中传递命令,而不是将其作为URL参数发送:
from subprocess import Popen, TimeoutExpired, PIPE
from flask import Flask, jsonify, abort, request
app = Flask(__name__)
@app.route("/", methods=["POST"])
def index():
req_json = request.get_json()
if req_json is None or "command" not in req_json:
abort(400, description="Please provide command in JSON request!")
proc = Popen(req_json["command"], stdout=PIPE, stderr=PIPE, shell=True)
try:
outs, errs = proc.communicate(timeout=1)
except TimeoutExpired:
proc.kill()
abort(500, description="The timeout is expired!")
if errs:
abort(500, description=errs.decode('utf-8'))
return jsonify(success=True, message=outs.decode('utf-8'))
@app.errorhandler(400)
def bad_request(error):
return jsonify(success=False, message=error.description), 400
@app.errorhandler(500)
def server_error(error):
return jsonify(success=False, message=error.description) , 500
将其保存到server.py
,然后运行:
$ FLASK_APP=server.py:app flask run
* Serving Flask app "server.py:app"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
请求示例:
$ curl -X POST -H "Content-Type: application/json" -d '{"command": "ls -l"}' localhost:5000
{"message":"total 8\ndrwxr-xr-x 2 const const 4096 Jul 19 09:52 __pycache__\n-rw-rw-r-- 1 const const 1043 Jul 19 09:52 server.py\n","success":true}
答案 2 :(得分:0)
您真的要这样做吗???
如果某个不受信任的人发现了此问题……您的服务器将很快死机。