code-server-liek
This commit is contained in:
@@ -5,154 +5,166 @@ import uuid
|
||||
import subprocess
|
||||
import threading
|
||||
from flask import Blueprint, request, current_app, session
|
||||
from flask_socketio import Namespace, join_room, leave_room, emit, SocketIO
|
||||
from flask_socketio import Namespace, join_room, leave_room, emit, SocketIO, rooms, disconnect
|
||||
from threading import Thread
|
||||
import sys
|
||||
from ..extensions import socketio
|
||||
|
||||
import pty
|
||||
import termios
|
||||
import struct
|
||||
import fcntl
|
||||
import psutil
|
||||
TERM_INIT_CONFIG = {
|
||||
# instead of local server runnning this web terminal service
|
||||
# "domain" is the target that you want to access through local server (with this web terminal)
|
||||
# and before doing so - make sure you have username and port (on the "domain") to implement remote access
|
||||
'domain': '127.0.0.1', # or ip address like 192.168.10.11
|
||||
'client_path': {
|
||||
'telnet': '/usr/bin/telnet', # confirmed location of your client binary (with cmd like 'which telnet')
|
||||
'ssh': '/usr/bin/ssh'
|
||||
}
|
||||
}
|
||||
terminal_bp = Blueprint('terminal', __name__, url_prefix='/vsc-like')
|
||||
|
||||
# 存储终端进程
|
||||
command_dict = {}
|
||||
terminal_busy = {}
|
||||
terminals = {}
|
||||
terminal_locks = {}
|
||||
|
||||
def check_process_running(command_name):
|
||||
try:
|
||||
# 使用 pgrep 查找与给定命令相关的进程
|
||||
result = subprocess.run(
|
||||
["pgrep", "-f", command_name],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE
|
||||
)
|
||||
return result.returncode == 0 # 如果返回值为 0,说明命令仍在运行
|
||||
except Exception as e:
|
||||
print(f"Error checking process: {e}")
|
||||
return False
|
||||
|
||||
def monitor_process(socket_id, command_name, namespace):
|
||||
while True:
|
||||
is_running = check_process_running(command_name)
|
||||
if is_running:
|
||||
print(f"Process '{command_name}' is still running.")
|
||||
else:
|
||||
print(f"Process '{command_name}' is not running.")
|
||||
break # 停止检查,如果进程不再运行
|
||||
|
||||
time.sleep(0.1) # 每 0.1 秒检查一次
|
||||
command_dict[socket_id] = ''
|
||||
terminal_busy[socket_id] = False
|
||||
namespace.emit('terminal_output',{'data': '>'})
|
||||
|
||||
|
||||
def start_terminal_process(socket_id, namespace):
|
||||
def set_winsize(fd, row, col, xpix=0, ypix=0):
|
||||
winsize = struct.pack("HHHH", row, col, xpix, ypix)
|
||||
fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
|
||||
|
||||
|
||||
def read_and_forward_pty_output(fd=None, pid=None, room_id=None,namespace=None):
|
||||
"""
|
||||
监听多个子进程的输出,并通过 WebSocket 发给前端
|
||||
使用 select 进行非阻塞的 I/O 操作,并实现动态流量控制
|
||||
read data on pty master from the pty slave, and emit to the web terminal visitor
|
||||
"""
|
||||
process = terminals[socket_id]
|
||||
|
||||
# 获取子进程的 stdout 和 stderr
|
||||
stdout = process.stdout
|
||||
stdin = process.stdin
|
||||
# 将 stdout 和 stderr 添加到 select 监听的文件描述符列表中
|
||||
|
||||
# 初始等待时间
|
||||
timeout = 0.1
|
||||
max_timeout = 2 # 设置最大超时时间为 2 秒
|
||||
|
||||
max_read_bytes = 1024 * 20
|
||||
timeout=0.1
|
||||
while True:
|
||||
while True:
|
||||
output = stdout.readline()
|
||||
if not output:
|
||||
break
|
||||
timeout = 0.1
|
||||
namespace.emit('terminal_output', {'data': output+'\r'}, room=socket_id)
|
||||
timeout = min(timeout * 2, max_timeout)
|
||||
time.sleep(timeout)
|
||||
if process.poll() is not None:
|
||||
break
|
||||
|
||||
socketio.sleep(timeout)
|
||||
timeout=min(timeout*2, 0.4)
|
||||
# using flask default web server, or uwsgi production web server
|
||||
# when the child process is terminated, it will not disappear from linux process list
|
||||
# and keep staying as a zombie process until the parent exits.
|
||||
try:
|
||||
child_process = psutil.Process(pid)
|
||||
except psutil.NoSuchProcess as err:
|
||||
return
|
||||
if child_process.status() not in ('running', 'sleeping'):
|
||||
return
|
||||
if fd:
|
||||
timeout_sec = 0
|
||||
(data_ready, _, _) = select.select([fd], [], [], timeout_sec)
|
||||
if data_ready:
|
||||
# output = os.read(fd, max_read_bytes).decode('ascii')
|
||||
timeout=0.1
|
||||
try:
|
||||
output = os.read(fd, max_read_bytes).decode()
|
||||
except Exception as err:
|
||||
output = """
|
||||
***AQUI WEB TERM ERR***
|
||||
{}
|
||||
***********************
|
||||
""".format(err)
|
||||
# the key for different visitor to get different terminal (instead of mixing up)
|
||||
# is to let the background task push pty response to each one's own (default) ROOM!
|
||||
namespace.emit("pty_output", {"output": output}, room=room_id)
|
||||
|
||||
class VSCLikeNameSpace(Namespace):
|
||||
def on_connect(self, data):
|
||||
"""
|
||||
处理 WebSocket 连接
|
||||
- 验证会话
|
||||
- 使用指定的用户启动 bash 终端
|
||||
- 启动监听子进程输出的线程
|
||||
"""
|
||||
socket_id = session.get('uuid')
|
||||
user_id = session.get('user_id') # 从 session 获取用户 ID
|
||||
path = session.get('path')
|
||||
def on_connect(self):
|
||||
"""new client connected"""
|
||||
if session.get('terminal_config', {}).get('child_pid', None):
|
||||
print(session['terminal_config']['child_pid'])
|
||||
# already started child process, don't start another
|
||||
return
|
||||
|
||||
if not path or not user_id:
|
||||
emit('error', {'message': 'Authentication failed, no path or user found for this session'})
|
||||
return False # 拒绝连接
|
||||
# 使用 sudo 启动终端进程,以指定的 user_id 用户身份执行
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
['sudo', '-u', user_id, 'bash', '-il'], # 使用指定的 user_id 启动 bash
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True, # 确保输出是文本格式
|
||||
)
|
||||
terminals[socket_id] = process
|
||||
terminal_busy[socket_id] = False
|
||||
emit('connected', {'message': 'OK'})
|
||||
join_room(socket_id, namespace='/vsc-like')
|
||||
# create child process attached to a pty we can read from and write to
|
||||
(child_pid, fd) = pty.fork()
|
||||
lesson_path = session.get('path')
|
||||
if child_pid == 0:
|
||||
# this is the child process fork.
|
||||
# anything printed here will show up in the pty, including the output
|
||||
# of this subprocess
|
||||
# subprocess.run('bash')
|
||||
term_type = session.get('terminal_config').get('term_type')
|
||||
path = TERM_INIT_CONFIG.get('client_path', {}).get(term_type, None)
|
||||
if not path:
|
||||
print("Can't locate {} binary, exit".format(term_type))
|
||||
disconnect()
|
||||
if term_type == 'telnet':
|
||||
# switch to the right location of your telnet binary (example comes from OSX which got telnet from brew)
|
||||
# or you can also make work like auto-detection, or manually but configurable
|
||||
os.execl(path, 'telnet', '-l', session['terminal_config']['username'],
|
||||
session['terminal_config']['domain'], '{}'.format(session['terminal_config']['port']))
|
||||
elif term_type == 'ssh':
|
||||
os.execl(path,'ssh', '-p','22',
|
||||
#'{}'.format(session['terminal_config']['port']),
|
||||
'{}@{}'.format(session['terminal_config']['username'], session['terminal_config']['domain']))
|
||||
|
||||
|
||||
socketio.start_background_task(target=start_terminal_process, socket_id=socket_id, namespace=self)
|
||||
|
||||
except Exception as e:
|
||||
emit('error', {'message': f'Error starting terminal process: {str(e)}'})
|
||||
return False
|
||||
|
||||
def on_send_input(self, data):
|
||||
socket_id = session.get('uuid')
|
||||
input_data = data.get('input')
|
||||
if socket_id not in command_dict:command_dict[socket_id]=''
|
||||
# 检查当前 socket_id 是否有对应的终端
|
||||
if socket_id in terminals:
|
||||
# 获取该终端的锁进行线程同步
|
||||
lock = terminal_locks.get(socket_id)
|
||||
if not lock:
|
||||
lock = threading.Lock()
|
||||
terminal_locks[socket_id] = lock
|
||||
|
||||
with lock: # 在锁的保护下操作终端
|
||||
try:
|
||||
terminals[socket_id].stdin.write(input_data)
|
||||
command_dict[socket_id]+=input_data
|
||||
if input_data=='\r':
|
||||
terminals[socket_id].stdin.flush()
|
||||
emit('terminal_output', {'data': f'\r\n'}, room=socket_id)
|
||||
if terminal_busy[socket_id]==False:
|
||||
terminal_busy[socket_id] = True
|
||||
socketio.start_background_task(monitor_process, socket_id, command_dict[socket_id], namespace=self)
|
||||
elif input_data=='\x03':
|
||||
terminals[socket_id].stdin.flush()
|
||||
emit('terminal_output', {'data': f'^C\x03\r\n'}, room=socket_id)
|
||||
else:
|
||||
emit('terminal_output', {'data': input_data}, room=socket_id)
|
||||
except Exception as e:
|
||||
emit('error', {'message': f'Error sending input: {str(e)}'}, room=socket_id)
|
||||
else:
|
||||
current_app.logger.debug("wrong term type {}".format(term_type))
|
||||
disconnect()
|
||||
session['terminal_config'] = TERM_INIT_CONFIG
|
||||
else:
|
||||
emit('error', {'message': 'No terminal found for this session'}, room=socket_id)
|
||||
session['terminal_config']['fd'] = fd
|
||||
session['terminal_config']['child_pid'] = child_pid
|
||||
session['terminal_config']['room_id'] = rooms()[0]
|
||||
session.modified = True
|
||||
set_winsize(fd, 50, 50)
|
||||
current_app.logger.debug("child pid = {}".format(child_pid))
|
||||
current_app.logger.debug("rooms of this session = {}".format(rooms()))
|
||||
socketio.start_background_task(read_and_forward_pty_output, fd, child_pid, rooms()[0],self)
|
||||
current_app.logger.debug("background task running")
|
||||
# print(session)
|
||||
|
||||
def on_disconnect():
|
||||
socket_id = session.get('uuid')
|
||||
|
||||
# 检查是否有终端进程需要终止
|
||||
if socket_id in terminals:
|
||||
try:
|
||||
# 终止终端进程
|
||||
terminals[socket_id].terminate()
|
||||
del terminals[socket_id]
|
||||
# 删除锁
|
||||
if socket_id in terminal_locks:
|
||||
del terminal_locks[socket_id]
|
||||
emit('terminal_output', {'data': 'Terminal disconnected and terminated'}, room=socket_id)
|
||||
except Exception as e:
|
||||
emit('error', {'message': f'Error disconnecting terminal: {str(e)}'}, room=socket_id)
|
||||
def on_pty_input(self, data):
|
||||
"""write to the child pty, which now is the ssh process from this machine to the 'domain' configured
|
||||
"""
|
||||
print(f"get data {data}")
|
||||
try:
|
||||
child_process = psutil.Process(session.get('terminal_config').get('child_pid'))
|
||||
except psutil.NoSuchProcess as err:
|
||||
disconnect()
|
||||
session['terminal_config'] = TERM_INIT_CONFIG
|
||||
return
|
||||
if child_process.status() not in ('running', 'sleeping'):
|
||||
disconnect()
|
||||
session['terminal_config'] = TERM_INIT_CONFIG
|
||||
return
|
||||
# print(session)
|
||||
# print(data, 'from input')
|
||||
fd = session.get('terminal_config').get('fd')
|
||||
if fd:
|
||||
# print("writing to ptd: %s" % data["input"])
|
||||
# os.write(fd, data["input"].encode('ascii'))
|
||||
os.write(fd, data["input"].encode())
|
||||
|
||||
|
||||
def on_resize(self, data):
|
||||
try:
|
||||
child_process = psutil.Process(session.get('terminal_config').get('child_pid'))
|
||||
except psutil.NoSuchProcess as err:
|
||||
disconnect()
|
||||
session['terminal_config'] = TERM_INIT_CONFIG
|
||||
return
|
||||
if child_process.status() not in ('running', 'sleeping'):
|
||||
disconnect()
|
||||
session['terminal_config'] = TERM_INIT_CONFIG
|
||||
return
|
||||
fd = session.get('terminal_config').get('fd')
|
||||
if fd:
|
||||
set_winsize(fd, data["rows"], data["cols"])
|
||||
|
||||
def on_disconnect(self):
|
||||
try:
|
||||
child_process = psutil.Process(session.get('terminal_config', {}).get('child_pid'))
|
||||
except psutil.NoSuchProcess as err:
|
||||
disconnect()
|
||||
session['terminal_config'] = TERM_INIT_CONFIG
|
||||
return
|
||||
if child_process.status() in ('running', 'sleeping'):
|
||||
# if visitor just close the browser tab then left alone the pty here
|
||||
# it should be terminated by the parent process after
|
||||
child_process.terminate()
|
||||
current_app.logger.debug('user left the pty alone, terminated')
|
||||
current_app.logger.debug('Client disconnected')
|
||||
@@ -12,8 +12,7 @@ def create_folder():
|
||||
filepath = request.json.get('path', '')
|
||||
path = session.get('path')
|
||||
parent = request.json.get('parent', '')
|
||||
root_workspace_path = current_app.config['ROOT_WORKSPACE_PATH']
|
||||
base_path = f'{root_workspace_path}/{path}'
|
||||
base_path = f'{path}'
|
||||
filepath = f'{base_path}/{parent}/{filepath}'
|
||||
try:
|
||||
os.makedirs(filepath)
|
||||
@@ -27,8 +26,7 @@ def create_file():
|
||||
filepath = request.json.get('path', '')
|
||||
path = session.get('path')
|
||||
parent = request.json.get('parent', '')
|
||||
root_workspace_path = current_app.config['ROOT_WORKSPACE_PATH']
|
||||
base_path = f'{root_workspace_path}/{path}'
|
||||
base_path = f'{path}'
|
||||
filepath = f'{base_path}/{parent}/{filepath}'
|
||||
try:
|
||||
open(filepath, 'w').close()
|
||||
@@ -41,8 +39,7 @@ def rename_file():
|
||||
user_root = session.get('path')
|
||||
path = request.json.get('path', '')
|
||||
new_name = request.json.get('newName', '')
|
||||
root_workspace_path = current_app.config['ROOT_WORKSPACE_PATH']
|
||||
base_path = f'{root_workspace_path}/{user_root}'
|
||||
base_path = f'{user_root}'
|
||||
filepath = f'{base_path}/{path}'
|
||||
try:
|
||||
path_list = filepath.split('/')
|
||||
@@ -58,8 +55,7 @@ def rename_folder():
|
||||
user_root = session.get('path')
|
||||
path = request.json.get('path', '')
|
||||
new_name = request.json.get('newName', '')
|
||||
root_workspace_path = current_app.config['ROOT_WORKSPACE_PATH']
|
||||
base_path = f'{root_workspace_path}/{user_root}'
|
||||
base_path = f'{user_root}'
|
||||
folderpath = f'{base_path}/{path}'
|
||||
try:
|
||||
path_list = folderpath.split('/')
|
||||
@@ -74,9 +70,8 @@ def rename_folder():
|
||||
def copy_files():
|
||||
old_path = request.json.get('oldPath', '')
|
||||
new_path = request.json.get('newPath', '')
|
||||
root_workspace_path = current_app.config['ROOT_WORKSPACE_PATH']
|
||||
user_root = session.get('path')
|
||||
base_path = f'{root_workspace_path}/{user_root}'
|
||||
base_path = f'{user_root}'
|
||||
old_path = f'{base_path}/{old_path}'
|
||||
new_path = f'{base_path}/{new_path}'
|
||||
# oldpath的父目录就是newpath的话,对oldpath进行重命名
|
||||
@@ -106,9 +101,8 @@ def copy_files():
|
||||
@file_bp.route('/delete-file', methods=['POST'])
|
||||
def delete_file():
|
||||
path = request.json.get('path', '')
|
||||
root_workspace_path = current_app.config['ROOT_WORKSPACE_PATH']
|
||||
user_root = session.get('path')
|
||||
base_path = f'{root_workspace_path}/{user_root}'
|
||||
base_path = f'{user_root}'
|
||||
filepath = f'{base_path}/{path}'
|
||||
if os.path.isdir(filepath):
|
||||
shutil.rmtree(filepath)
|
||||
@@ -119,8 +113,7 @@ def delete_file():
|
||||
@file_bp.route('/file-content', methods=['POST'])
|
||||
def file_content():
|
||||
path = session.get('path')
|
||||
root_workspace_path = current_app.config['ROOT_WORKSPACE_PATH']
|
||||
base_path = f'{root_workspace_path}/{path}'
|
||||
base_path = f'{path}'
|
||||
filepath = request.json.get('path', '')
|
||||
filepath = f'{base_path}/{filepath}'
|
||||
if not os.path.exists(filepath):
|
||||
@@ -135,8 +128,7 @@ def file_content():
|
||||
@file_bp.route('/save-file', methods=['POST'])
|
||||
def save_file():
|
||||
path = session.get('path')
|
||||
root_workspace_path = current_app.config['ROOT_WORKSPACE_PATH']
|
||||
base_path = f'{root_workspace_path}/{path}'
|
||||
base_path = f'{path}'
|
||||
filepath = request.json.get('path', '')
|
||||
filepath = f'{base_path}/{filepath}'
|
||||
content = request.json.get('content', '')
|
||||
|
||||
@@ -4,9 +4,18 @@ from flask import Blueprint, request, jsonify, current_app, render_template, ses
|
||||
from ..services.file_service import get_file_tree, load_config
|
||||
|
||||
main_bp = Blueprint('main', __name__, url_prefix='/vsc-like')
|
||||
|
||||
@main_bp.route('/<user_uuid>/<user_id>/<course_id>/<chapter_name>/<lesson_name>', methods=['GET'])
|
||||
def vsc_like(user_uuid, user_id, course_id, chapter_name, lesson_name):
|
||||
TERM_INIT_CONFIG = {
|
||||
# instead of local server runnning this web terminal service
|
||||
# "domain" is the target that you want to access through local server (with this web terminal)
|
||||
# and before doing so - make sure you have username and port (on the "domain") to implement remote access
|
||||
'domain': '15.168.14.27', # or ip address like 192.168.10.11
|
||||
'client_path': {
|
||||
'telnet': '/usr/bin/telnet', # confirmed location of your client binary (with cmd like 'which telnet')
|
||||
'ssh': '/usr/bin/ssh'
|
||||
}
|
||||
}
|
||||
@main_bp.route('/<user_uuid>/<user_id>/<course_id>/<chapter_name>/<lesson_name>/<port>', methods=['GET'])
|
||||
def vsc_like(user_uuid, user_id, course_id, chapter_name, lesson_name, port):
|
||||
uuid = user_uuid
|
||||
base_path = current_app.config['ROOT_WORKSPACE_PATH']
|
||||
path = os.path.join(base_path, user_id, course_id, chapter_name, lesson_name)
|
||||
@@ -16,6 +25,11 @@ def vsc_like(user_uuid, user_id, course_id, chapter_name, lesson_name):
|
||||
session['course_id'] = course_id
|
||||
session['chapter_name'] = chapter_name
|
||||
session['lesson_name'] = lesson_name
|
||||
session['terminal_config'] = TERM_INIT_CONFIG
|
||||
session['terminal_config']['term_type'] = 'ssh'
|
||||
session['terminal_config']['username'] = user_id
|
||||
session['terminal_config']['port'] = port
|
||||
session.modified = True
|
||||
config = load_config(path)
|
||||
# if not config:
|
||||
# return jsonify({"error": "Configuration file not found or invalid"}), 404
|
||||
@@ -26,11 +40,17 @@ def vsc_like(user_uuid, user_id, course_id, chapter_name, lesson_name):
|
||||
try:
|
||||
subprocess.run(["sudo", "useradd", "-m", "-d", user_root, user_id]) # 创建用户
|
||||
subprocess.run(["sudo", "chown", "-R", user_id, user_root]) # 设置目录权限为新用户
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"Error creating user {user_id}: {e}")
|
||||
try:
|
||||
# 使用 sudo 执行 mkdir 命令来创建目录
|
||||
subprocess.run(["sudo", "-u", user_id, "mkdir", "-p", path], check=True)
|
||||
subprocess.run(["sudo", "-u", user_id, "mkdir", "-p", f'{user_root}/.ssh'], check=True)
|
||||
flask_pub_key = "/home/flask/.ssh/id_ed25519.pub"
|
||||
subprocess.run(["sudo", "cp", flask_pub_key, f"{user_root}/.ssh/authorized_keys"], check=True)
|
||||
subprocess.run(["sudo", "chmod", "700", f"{user_root}/.ssh"], check=True)
|
||||
subprocess.run(["sudo", "chmod", "600", f"{user_root}/.ssh/authorized_keys"], check=True)
|
||||
print(f"Directory {path} created successfully for user {user_id}")
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"Error creating directory {path} details {str(e)}")
|
||||
@@ -44,17 +64,15 @@ def vsc_like(user_uuid, user_id, course_id, chapter_name, lesson_name):
|
||||
subprocess.run(["sudo", "usermod", "-a", "-G", f"shared_group_{user_id}", 'flask'], check=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"Error adding user {user_id} to shared_group: {e}")
|
||||
try:#将文件
|
||||
subprocess.run(["sudo", "chown", "-R", f"flask:shared_group_{user_id}", user_root], check=True)
|
||||
try:
|
||||
subprocess.run(["sudo", "chown", "-R", f"flask:shared_group_{user_id}", path], check=True)
|
||||
subprocess.run(["sudo", "chmod", "-R", "750", user_root], check=True)
|
||||
subprocess.run(["sudo", "chmod", "-R", "770", path], check=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"Error changing directory {path} to shared_group_{user_id}: {e}")
|
||||
try:#继承目录
|
||||
subprocess.run(["sudo", "chmod", "g+s", path], check=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"Error changing directory {path} to shared_group_{user_id}: {e}")
|
||||
|
||||
|
||||
return render_template('index.html')
|
||||
|
||||
|
||||
|
||||
return render_template('index.html', course_id=course_id, chapter_name=chapter_name, lesson_name=lesson_name)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user