import os import select import time 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, 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') 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): """ read data on pty master from the pty slave, and emit to the web terminal visitor """ max_read_bytes = 1024 * 20 timeout=0.1 try: while True: 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: # Process already terminated, clean up any zombie try: os.waitpid(pid, os.WNOHANG) except Exception: pass return if child_process.status() not in ('running', 'sleeping'): # Process is terminated or in other state, clean up try: child_process.wait(timeout=1) except Exception: try: os.waitpid(pid, os.WNOHANG) except Exception: pass 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) finally: # Clean up file descriptor if it's open if fd: try: os.close(fd) except Exception: pass class VSCLikeNameSpace(Namespace): 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 # 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'])) else: current_app.logger.debug("wrong term type {}".format(term_type)) disconnect() session['terminal_config'] = TERM_INIT_CONFIG else: 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_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): child_pid = session.get('terminal_config', {}).get('child_pid') if child_pid: try: child_process = psutil.Process(child_pid) 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() # Wait for the process to terminate and collect its exit status child_process.wait(timeout=2) current_app.logger.debug('user left the pty alone, terminated and waited') except psutil.NoSuchProcess as err: # Process already terminated, try to wait anyway to clean up any zombie try: os.waitpid(child_pid, os.WNOHANG) except Exception: pass except psutil.TimeoutExpired: # If process didn't terminate in time, kill it forcefully child_process.kill() try: child_process.wait(timeout=1) except Exception: pass except Exception as err: current_app.logger.error(f'Error terminating process: {err}') finally: # Close the file descriptor if it's open fd = session.get('terminal_config', {}).get('fd') if fd: try: os.close(fd) except Exception: pass # Reset session config session['terminal_config'] = TERM_INIT_CONFIG current_app.logger.debug('Client disconnected')