如何在Flask中执行Shell命令并在网页显示输出
解决Flask执行Shell命令并在页面显示输出的问题
问题根源
你之前的页面空白是两个核心问题导致的:
index()视图函数没有返回任何响应内容- 模板缺少接收并渲染命令输出的逻辑
完整解决方案
1. 补全app.py代码
使用subprocess.run()执行命令,捕获输出后传递给模板:
from flask import Flask, render_template import subprocess app = Flask(__name__) @app.route('/') @app.route('/ls') # 同时支持根路径和/ls路径访问 def index(): # 执行shell命令,捕获标准输出与错误输出 result = subprocess.run( ['ls', '-lh', '/home'], # 用列表传参避免shell注入风险 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, # 将错误输出合并到标准输出 text=True # 直接获取字符串格式输出,无需手动解码 ) # 将命令结果传递给模板渲染 return render_template('index.html', output=result.stdout) if __name__ == '__main__': app.run(debug=True)
重要提醒:绝对不要在生产环境中直接执行Shell命令,尤其是涉及用户输入的场景。示例中用列表传参是为了降低安全风险,禁止使用
shell=True选项(除非你完全掌控所有输入)。
2. 完善模板文件
首先确保存在templates/base.html父模板(如果没有则新建):
<!DOCTYPE html> <html> <head> <title>Shell Command Output</title> </head> <body> {% block content %}{% endblock %} </body> </html>
然后修改templates/index.html,接收并格式化显示输出:
{% extends 'base.html' %} {% block content %} <pre>{{ output }}</pre> {% endblock %}
验证运行
- 启动Flask应用:
python app.py - 访问
http://localhost:5000或http://localhost:5000/ls,即可看到ls -lh /home的完整输出。
如果命令执行出错(比如目标路径不存在),错误信息也会直接显示在页面上,方便排查问题。
内容的提问来源于stack exchange,提问作者Saeed
相关产品推荐
相关产品推荐

