def start(self, evtcallback, cursorcallback): """ Launches the TerminalSession's process and adds to it the given callback to deal with modified lines. The callback takes the form callback(line_number, line). """ if self.running: raise SessionStateError("TerminalSession already running") self.running = True self.stream = pyte.ByteStream() self.screen = pyte.DiffScreen(self.params["cols"], self.params["rows"]) # self.screen.set_mode(pyte.modes.LNM) # This treats \ns as \r\ns. # Is this necessary/reasonable? self.stream.attach(self.screen) child_pid, self.child_fd = pty.fork() os.chdir(self.working_dir) os.environ['HOME'] = self.home_dir if not child_pid: # under what circumstances would it not be 0? os.execv(self.cmd, self.args) attr = termios.tcgetattr(self.child_fd) attr[3] = attr[3] & ~termios.ECHO # Disable echoing termios.tcsetattr(self.child_fd, termios.TCSANOW, attr) winsize = struct.pack("HHHH", self.params["rows"], self.params["cols"], 0, 0) fcntl.ioctl(self.child_fd, termios.TIOCSWINSZ, winsize) # set size self.callback = evtcallback self.cursor_callback = cursorcallback
def __init_screen_stream(self): """ Initializing the virtual screen and the character stream """ self._stream = pyte.ByteStream() self._screen = pyte.Screen(80, 24) self._stream.attach(self._screen)
def __init__(self, name: str, sh_path: str, su_path: str = None, login: str = None, password: str = None, on_change=None): self.name = name self.sh_path = sh_path self.su_path = su_path self.login = login self.password = password self.on_change = on_change self.controls = {} self.interactive = False self.auto_submit = True self.state: TerminalState = TerminalState.CLOSED self.screen = pyte.Screen(80, 24) self.stream = pyte.ByteStream(self.screen) self.fd = None self.content = None self.content_update = False
def test_byte_stream_define_charset(charset, mapping): screen = pyte.Screen(3, 3) stream = pyte.ByteStream(screen) stream.select_other_charset("@") stream.feed((ctrl.ESC + "(" + charset).encode()) assert screen.display[0] == " " * 3 assert screen.g0_charset == mapping
def test_debug_stream(input, expected): output = StringIO() stream = pyte.ByteStream(pyte.DebugScreen(to=output)) stream.feed(input) output.seek(0) assert [eval(line) for line in output] == expected
def send(self, text, silent=None): if hasattr(text, 'encode'): text = text.encode() text += b'\r' self.terminal.tx(text) # Wait for ok stream = pyte.ByteStream() width = 1000 screen = pyte.Screen(width, 10) stream.attach(screen) incoming = io.BytesIO() if silent is None: silent = self.silent timeout = time.time() + 3 while True: if time.time() > timeout: raise ValueError('Timeout') data = self.terminal.rx(silent=silent) if not data: continue stream.feed(data) incoming.write(data) incoming.seek(-4, io.SEEK_END) if incoming.read() == b'>>> ': output = io.StringIO() for line in screen.display: line = line.strip() output.write(line) if len(line) < width: output.write(u'\n') return output.getvalue().rstrip()[:-3]
def __init__(self, columns, lines, p_in): self.screen = pyte.DiffScreen(columns, lines) self.screen.set_mode(pyte.modes.LNM) self.screen.write_process_input = \ lambda data: p_in.write(data.encode()) self.stream = pyte.ByteStream() self.stream.attach(self.screen)
def _fake_terminal(self): logging.debug( "Sniffer: Creating Pyte screen with cols %i and rows %i" % (self.term_cols, self.term_rows)) self.screen = pyte.Screen(self.term_cols, self.term_rows) self.stream = pyte.ByteStream() self.stream.attach(self.screen)
def __init_screen_stream(self): """ 初始化虚拟屏幕和字符流 """ self.stream = pyte.ByteStream() self.screen = pyte.Screen(80, 24) self.stream.attach(self.screen)
def process_ssh(data): msg_type = data[1] sid = get_session_id(data) msg = data[18:] session = sessions[sid] if msg_type == 0x00: # connection ip = '.'.join(str(i) for i in msg[:4]) port = msg[4] * 256 + msg[5] session['data'] = { 'sessionID': sid, 'svrType': 'ssh', 'potIP': POT_IP, 'portPort': 22, 'attackIP': ip, 'attackPort': port, 'blastList': [], 'execCommands': [], 'startTime': datetime.datetime.now().isoformat(), 'resize': 0, 'strokes': [] } elif msg_type == 0x01: # login username_len = msg[0] username = str(msg[1:username_len + 1]) password_len = msg[username_len + 1] password = str(msg[username_len + 2:]) session['data']['blastList'].append('%s::%s' % (username, password)) elif msg_type == 0x02: # session pair = session['data']['blastList'][-1].split('::') session['data']['loginName'] = pair[0] session['data']['loginPasswd'] = pair[1] screen = pyte.HistoryScreen(80, 24, history=1000, ratio=1) stream = pyte.ByteStream(screen) session['screen'] = screen session['stream'] = stream elif msg_type == 0x03: # window resize r = msg[0] c = msg[1] session['screen'].resize(r, c) session['data']['resize'] += 1 elif msg_type == 0x04: # data message session['stream'].feed(msg) session['data']['strokes'].append(msg) elif msg_type == 0x05: # disconnection session['data']['endTime'] = datetime.datetime.now().isoformat() if 'screen' in session: screen = session['screen'] while screen.history.position > screen.lines and screen.history.top: screen.prev_page() data = '' rest_lines = 0 while screen.history.position < screen.history.size and screen.history.bottom: data += '\n'.join(screen.display) + '\n' rest_lines = len(screen.history.bottom) screen.next_page() data += '\n'.join(screen.display[-rest_lines:]) + '\n' sha256 = send_content(data) send(session['data'], sha256, 'ssh') del sessions[sid]
def __init__(self, MudData): self.screensize = (150, 80) self.screen = pyte.Screen(self.screensize[0], self.screensize[1]) self.stream = pyte.ByteStream(self.screen) self.telnetConnection = telnetlib.Telnet() self.MudDataInner = MudData self.telnetConnection.set_option_negotiation_callback( self.handle_option_negotiations)
def __init__(self, columns, lines, p_in): self.text = '' self.attributes = None self.screen = fenrirScreen(columns, lines) self.screen.write_process_input = \ lambda data: p_in.write(data.encode()) self.stream = pyte.ByteStream() self.stream.attach(self.screen)
def test_byte_stream_feed(): screen = pyte.Screen(20, 1) screen.draw = handler = argcheck() stream = pyte.ByteStream(screen) stream.feed("Нерусский текст".encode("utf-8")) assert handler.count == 1 assert handler.args == ("Нерусский текст", )
def __init__(self, host=None): self.buf = '' self.cur_board = None self.screen = pyte.Screen(80, 24) self.stream = pyte.ByteStream(encodings = [("big5hkscs", "replace")]) self.stream.attach(self.screen) self.tn = Telnet(host) self.state = "connected"
def __init_screen_stream(self): """ 初始化虚拟屏幕和字符流 """ self.stream = pyte.ByteStream() self.screen = pyte.Screen(80, 24) #Adds a given screen to the listener queue self.stream.attach(self.screen)
def feedbuffer(self, data): try: self.termstream.feed(data) except StopIteration: # corrupt parser state, start over self.termstream = pyte.ByteStream() self.termstream.attach(self.buffer) except Exception: _tracelog.log(traceback.format_exc(), ltype=log.DataTypes.event, event=log.Events.stacktrace)
def test_byte_stream_define_charset_unknown(): screen = pyte.Screen(3, 3) stream = pyte.ByteStream(screen) stream.select_other_charset("@") default_g0_charset = screen.g0_charset # ``"Z"`` is not supported by Linux terminal, so expect a noop. assert "Z" not in cs.MAPS stream.feed((ctrl.ESC + "(Z").encode()) assert screen.display[0] == " " * 3 assert screen.g0_charset == default_g0_charset
def test_draw_cp437(): screen = pyte.Screen(5, 1) stream = pyte.ByteStream(screen) assert screen.charset == 0 screen.define_charset("U", "(") stream.select_other_charset("@") stream.feed("α ± ε".encode("cp437")) assert screen.display == ["α ± ε"]
def curses_main(stdscr): # ugh curses.use_default_colors() curses.init_pair(1, -1, -1) curses.init_pair(2, curses.COLOR_YELLOW, -1) curses.init_pair(3, curses.COLOR_CYAN, -1) curses.init_pair(4, curses.COLOR_GREEN, -1) curses.init_pair(5, curses.COLOR_MAGENTA, -1) curses.init_pair(6, curses.COLOR_BLACK, -1) curses.init_pair(7, curses.COLOR_RED, -1) curses.init_pair(8, curses.COLOR_BLUE, -1) screen = pyte.Screen(79, 24) stream = pyte.ByteStream(screen) pid, amaster = pty.fork() if pid == 0: # chile os.execvpe("/usr/games/nethack", ["/usr/games/nethack"], env=dict(TERM="linux", COLUMNS="79", LINES="24", NETHACKOPTIONS=f"{os.getenv('HOME')}/.nethackrc")) exit(-1) # python3 broke setting stdin unbuffered. Thanks, python3. stdin = os.fdopen(sys.stdin.fileno(), "rb", buffering=0) tty.setcbreak(stdin, termios.TCSANOW) # this wasn't python3, but I'm still mad about it because of how long it # took to figure out amaster = os.fdopen(amaster, "w+b", buffering=0) update_screen(stdscr, screen) inqueue = [] while True: wl = [] if len(inqueue) == 0 else [amaster] rl, wl, xl = select.select([amaster, stdin], wl, [amaster, stdin]) if xl != []: break if amaster in rl: data = amaster.read(1024) stream.feed(data) update_screen(stdscr, screen) pass if stdin in rl: elt = sys.stdin.read(1) inqueue.append(elt) pass if len(inqueue) != 0 and amaster.writable: elt = inqueue.pop(0) amaster.write(elt.encode()) pass continue os.kill(pid, signal.SIGTERM) pass
def test_input_output(name): with open(os.path.join(captured_dir, name + ".input"), "rb") as handle: input = handle.read() with open(os.path.join(captured_dir, name + ".output")) as handle: output = json.load(handle) screen = pyte.Screen(80, 24) stream = pyte.ByteStream(screen) stream.feed(input) assert screen.display == output
def __init__(self, node, configmanager, width=80, height=24): self.clearpending = False self.clearerror = False self.initsize = (width, height) self._dologging = True self._is_local = True self._isondemand = False self.error = None self._retrytime = 0 self.cfgmgr = configmanager self.node = node self.connectstate = 'unconnected' self._isalive = True self.buffer = pyte.Screen(100, 31) self.termstream = pyte.ByteStream() self.termstream.attach(self.buffer) self.livesessions = set([]) self.utf8decoder = codecs.getincrementaldecoder('utf-8')() if self._logtobuffer: self.logger = log.Logger(node, console=True, tenant=configmanager.tenant) (text, termstate, timestamp) = (b'', 0, False) # when reading from log file, we will use wall clock # it should usually match walltime. self.lasttime = 0 if timestamp: timediff = time.time() - timestamp if timediff > 0: self.lasttime = util.monotonic_time() - timediff else: # wall clock has gone backwards, use current time as best # guess self.lasttime = util.monotonic_time() self.clearbuffer() self.appmodedetected = False self.shiftin = None self.reconnect = None if termstate & 1: self.appmodedetected = True if termstate & 2: self.shiftin = b'0' self.users = {} self._attribwatcher = None self._console = None self.connectionthread = None self.send_break = None if self._genwatchattribs: self._attribwatcher = self.cfgmgr.watch_attributes( (self.node, ), self._genwatchattribs, self._attribschanged) self.check_isondemand() if not self._isondemand: self.connectstate = 'connecting' eventlet.spawn(self._connect)
def feedbuffer(self, data): if not isinstance(data, bytes): data = data.encode('utf-8') try: self.termstream.feed(data) except StopIteration: # corrupt parser state, start over self.termstream = pyte.ByteStream() self.termstream.attach(self.buffer) except Exception: _tracelog.log(traceback.format_exc(), ltype=log.DataTypes.event, event=log.Events.stacktrace)
def __init__(self, window_size=None, newline="\r\n", encoding=('UTF-8', 'ignore')): self._rows, self._columns = window_size or (200, 200) self._newline = newline self._stream = pyte.ByteStream(encodings=[encoding]) self._screen = pyte.HistoryScreen(self._rows, self._columns, history=100000) self._stream.attach(self._screen) self._screen.set_charset('B', '(') self._buffer = '' self._whitespace_after_last_feed = ''
def __init__(self, joeexe, joeargs, joeenv, startup, pid, fd): self.joeexe = joeexe self.joeargs = joeargs self.joeenv = joeenv self.pid = pid self.fd = fd self.exited = None self.term = pyte.Screen(startup.columns, startup.lines) self.stream = pyte.ByteStream() self.stream.attach(self.term) self.timeout = 1
def setUp(self): self.stdout = sys.stdout self.screen = pyte.Screen(60, 6) self.stream = pyte.ByteStream(self.screen) if platform.system() == 'Windows': self.WinDLL = ctypes.WinDLL ctypes.WinDLL = lambda name, *args, **kwargs: kernel32( self.screen) if name == 'kernel32' else self.WinDLL( name, *args, **kwargs) else: self.screen.set_mode(pyte.modes.LNM) self.fdread, fdwrite = os.pipe() self.fdwrite = os.dup(fdwrite) sys.stdout = os.fdopen(fdwrite, 'w', buffering=1)
def test_debug_stream(): tests = [ (b"foo", "DRAW foo"), (b"\x1b[1;24r\x1b[4l\x1b[24;1H", "SET_MARGINS 1; 24\nRESET_MODE 4\nCURSOR_POSITION 24; 1"), ] for input, expected in tests: output = StringIO() stream = pyte.ByteStream(pyte.DebugScreen(to=output)) stream.feed(input) lines = [l.rstrip() for l in output.getvalue().splitlines()] assert lines == expected.splitlines()
def __init__(self, id, title, command_line=None, log_file=None): self.id = id self.title = title self.command_line = command_line self.start_time = time.time() self.screen = pyte.Screen(145, 140) self.stream = pyte.ByteStream() self.stream.attach(self.screen) self.status = "running" self.is_running = True self.lock = threading.Lock() self.is_canceled = False self.log_file = log_file
def test_byte_stream_select_other_charset(): stream = pyte.ByteStream(pyte.Screen(3, 3)) assert stream.use_utf8 # on by default. # a) disable utf-8 stream.select_other_charset("@") assert not stream.use_utf8 # b) unknown code -- noop stream.select_other_charset("X") assert not stream.use_utf8 # c) enable utf-8 stream.select_other_charset("G") assert stream.use_utf8
def vimanim(code, input_filename, output_filename, font_path, font_size, columns, lines, long_delay, short_delay): # Load the specified font. font = ImageFont.truetype(font_path, font_size) # Launch vim. screen = pyte.Screen(columns, lines) stream = pyte.ByteStream(screen) child = pexpect.spawn('vim', ['-n', '-u', 'NONE'] + ([input_filename] if input_filename else [])) child.setwinsize(lines, columns) delay = long_delay # Render first frame. child.expect(pexpect.TIMEOUT, timeout=0.1) stream.feed(child.before) frames = [render_screen(screen, font)] durations = [delay * 2] # Render a frame for each keystroke. for c in code: if c == '「': delay = short_delay continue elif c == '」': delay = long_delay continue elif c == '・': frames.append(render_screen(screen, font)) durations.append(delay) continue child.send(c) child.expect(pexpect.TIMEOUT, timeout=0.1) stream.feed(child.before) frames.append(render_screen(screen, font, keyname(c))) durations.append(delay) # Render last frame. frames.append(render_screen(screen, font)) durations.append(delay * 3) # Save image. frames = [frame.convert('P', dither=Image.NONE) for frame in frames] frames[0].save(output_filename, save_all=True, append_images=frames[1:], duration=durations, loop=0)
def open(self): self.stream = pyte.ByteStream() self.screen = pyte.Screen(80, 24) self.stream.attach(self.screen) self.proc = tornado.process.Subprocess( self.cmd, env=self.env, shell=False, stdin=tornado.process.Subprocess.STREAM, stdout=tornado.process.Subprocess.STREAM, stderr=tornado.process.Subprocess.STREAM) self.stdout = self.proc.stdout self.stderr = self.proc.stderr self.stdin = self.proc.stdin self.stdout.read_until_close(callback=self.on_close, streaming_callback=self.on_process_read) self.stderr.read_until_close(callback=self.on_close, streaming_callback=self.on_process_read)