跳到主要内容

示例:网页执行 shell 命令

前言

网页输入shell命令,返回输出结果

示例代码

from flask import Flask, render_template, request
import subprocess

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
result = None
command = None
if request.method == 'POST':
command = request.form["command"]
result = subprocess.run(command, shell=True, capture_output=True, text=True)
result = result.stdout
return render_template('index.html', command=command, result=result)

if __name__ == '__main__':
app.run(host="0.0.0.0",port=5000,debug=False)

templates/index.html

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>Web Shell</title>
<style>
.container {
margin: 20px;
padding: 20px;
border: 1px solid #ccc;
}
</style>
</head>

<body>
<div class="container">
<h2>输入Shell命令:</h2>
<form method="post">
<input type="text" name="command" placeholder="Enter command" required>
<input type="submit" value="提交">
</form>
</div>
{% if result %}
<div class="container">
<h2>Shell命令:</h2>
<pre>{{ command }}</pre>
<h2>执行结果:</h2>
<pre>{{ result }}</pre>
</div>
{% endif %}
</body>

</html>