File size: 1,307 Bytes
bd4a0de 22711ef bd4a0de 22711ef 94cde56 22711ef bd4a0de 22711ef bd5ea1d bd4a0de ed198dd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
import subprocess
import os
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
# 设置工作目录
WORKING_DIR = '/tmp'
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('execute_command')
def handle_command(command):
try:
# 切换到工作目录
os.chdir(WORKING_DIR)
# 执行命令并捕获输出
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
emit('command_output', {'output': output.strip()})
# 捕获错误输出
error = process.stderr.read()
if error:
emit('command_output', {'output': error.strip()})
# 发送命令执行结束信号
emit('command_output', {'output': '[Command execution finished]'})
except Exception as e:
emit('command_output', {'output': str(e)})
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=7860, allow_unsafe_werkzeug=True) |