File size: 1,060 Bytes
bd4a0de 95ce585 22711ef 95ce585 bd4a0de 95ce585 bd4a0de 95ce585 22711ef bd4a0de 95ce585 bd4a0de 95ce585 |
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 |
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
import pty
import os
import subprocess
import threading
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
socketio = SocketIO(app)
def run_shell():
master_fd, slave_fd = pty.openpty()
process = subprocess.Popen(['bash'], stdin=slave_fd, stdout=slave_fd, stderr=slave_fd, text=True)
while True:
output = os.read(master_fd, 1024).decode('utf-8')
if output:
socketio.emit('output', output)
# 这里可以添加一个小的延迟,避免CPU占用过高
socketio.sleep(0.1)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('input')
def handle_input(input_data):
# 将输入写入伪终端
os.write(shell_master_fd, (input_data + '\n').encode('utf-8'))
if __name__ == '__main__':
shell_master_fd, shell_slave_fd = pty.openpty()
shell_thread = threading.Thread(target=run_shell)
shell_thread.start()
socketio.run(app, host='0.0.0.0', port=7860)
|