2017-08-21 07:12:15 -04:00
|
|
|
import os
|
|
|
|
import pty
|
|
|
|
import shlex
|
|
|
|
import signal
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
|
|
|
|
import pyte
|
|
|
|
|
|
|
|
class Terminal:
|
|
|
|
def __init__(self, columns, lines, p_in):
|
|
|
|
self.screen = pyte.HistoryScreen(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 feed(self, data):
|
|
|
|
self.stream.feed(data)
|
|
|
|
def dump(self):
|
|
|
|
cursor = self.screen.cursor
|
|
|
|
lines = []
|
|
|
|
for y in self.screen.dirty:
|
|
|
|
line = self.screen.buffer[y]
|
|
|
|
data = [(char.data, char.reverse, char.fg, char.bg)
|
|
|
|
for char in (line[x] for x in range(self.screen.columns))]
|
|
|
|
lines.append((y, data))
|
|
|
|
self.screen.dirty.clear()
|
|
|
|
return {"c": (cursor.x, cursor.y), "lines": lines}
|
|
|
|
|
|
|
|
|
|
|
|
def open_terminal(command="bash", columns=80, lines=24):
|
|
|
|
p_pid, master_fd = pty.fork()
|
|
|
|
if p_pid == 0: # Child.
|
|
|
|
argv = shlex.split(command)
|
|
|
|
env = dict(TERM="linux", LC_ALL="de_DE.UTF-8",
|
|
|
|
COLUMNS=str(columns), LINES=str(lines))
|
|
|
|
os.execvpe(argv[0], argv, env)
|
|
|
|
# File-like object for I/O with the child process aka command.
|
|
|
|
p_out = os.fdopen(master_fd, "w+b", 0)
|
|
|
|
return Terminal(columns, lines, p_out), p_pid, p_out
|
|
|
|
|
|
|
|
def convert_to_text(dump):
|
|
|
|
lines = dump['lines']
|
|
|
|
strLines = ''
|
|
|
|
for line in lines:
|
|
|
|
strLines += str(line[0])
|
|
|
|
for c in line[1]:
|
|
|
|
strLines += c[0]
|
|
|
|
return strLines
|
|
|
|
|
|
|
|
t,p,o = open_terminal()
|
|
|
|
t.feed(o.read(10000))
|
|
|
|
convert_to_text(t.dump())
|
|
|
|
t.feed(b'ls\r')
|
|
|
|
t.feed(o.read(10000))
|
|
|
|
convert_to_text(t.dump())
|
2017-08-21 11:45:03 -04:00
|
|
|
|
|
|
|
|
|
|
|
def HandleTerminal():
|
|
|
|
terminal, p_pid, p_out, master_fd = open_terminal()
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
r, w, x = select.select([p_out, master_fd],[],[],500000)
|
|
|
|
if r == []:
|
|
|
|
continue
|
|
|
|
for fd in r:
|
|
|
|
print(fd,r)
|
|
|
|
msg = fd.read(65536)
|
|
|
|
if fd == p_out:
|
|
|
|
terminal.feed(msg)
|
|
|
|
master_fd.write(msg)
|
|
|
|
if fd == master_fd:
|
|
|
|
terminal.feed(msg)
|
|
|
|
p_out.write(msg
|
|
|
|
print(terminal.screen.display)
|
|
|
|
except Exception as e: # Process died?
|
|
|
|
print(e)
|
|
|
|
#finally:
|
|
|
|
# os.kill(p_pid, signal.SIGTERM)
|
|
|
|
# p_out.close()
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
HandleTerminal()
|