Skip to content
Snippets Groups Projects
Commit ba4e096c authored by tuhe's avatar tuhe
Browse files

initial bootstrap stuff

parent 0b1eb36e
No related branches found
No related tags found
No related merge requests found
#!/usr/bin/env python3
import argparse
from flask import Flask, render_template
from flask_socketio import SocketIO
import pty
import os
import subprocess
import select
import termios
import struct
import fcntl
import shlex
import logging
import sys
logging.getLogger("werkzeug").setLevel(logging.ERROR)
__version__ = "0.5.0.0"
app = Flask(__name__, template_folder="templates", static_folder="static", static_url_path="/static")
app.config["SECRET_KEY"] = "secret!"
app.config["fd"] = None
app.config["child_pid"] = None
socketio = SocketIO(app)
def set_winsize(fd, row, col, xpix=0, ypix=0):
logging.debug("setting window size with termios")
winsize = struct.pack("HHHH", row, col, xpix, ypix)
fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
def read_and_forward_pty_output():
max_read_bytes = 1024 * 20
while True:
socketio.sleep(0.01)
if app.config["fd"]:
timeout_sec = 0
(data_ready, _, _) = select.select([app.config["fd"]], [], [], timeout_sec)
if data_ready:
output = os.read(app.config["fd"], max_read_bytes).decode()
socketio.emit("pty-output", {"output": output, 'hidden': 'rando'}, namespace="/pty")
@app.route("/terminal")
def manic_term():
pass
@app.route("/bootstrap")
def bootstrap():
return render_template("bootstrap.html")
@app.route("/")
def index():
return render_template("index.html")
@socketio.on("pty-input", namespace="/pty")
def pty_input(data):
"""write to the child pty. The pty sees this as if you are typing in a real
terminal.
"""
if app.config["fd"]:
logging.debug("received input from browser: %s" % data["input"])
os.write(app.config["fd"], data["input"].encode())
@socketio.on("resize", namespace="/pty")
def resize(data):
if app.config["fd"]:
logging.debug(f"Resizing window to {data['rows']}x{data['cols']}")
set_winsize(app.config["fd"], data["rows"], data["cols"])
@socketio.on("connect", namespace="/pty")
def connect():
"""new client connected"""
logging.info("new client connected")
if app.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()
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(app.config["cmd"])
else:
# this is the parent process fork.
# store child fd and pid
app.config["fd"] = fd
app.config["child_pid"] = child_pid
set_winsize(fd, 50, 50)
cmd = " ".join(shlex.quote(c) for c in app.config["cmd"])
# logging/print statements must go after this because... I have no idea why
# but if they come before the background task never starts
socketio.start_background_task(target=read_and_forward_pty_output)
logging.info("child pid is " + child_pid)
logging.info(
f"starting background task with command `{cmd}` to continously read "
"and forward pty output to client"
)
logging.info("task started")
def main():
parser = argparse.ArgumentParser(
description=(
"A fully functional terminal in your browser. "
"https://github.com/cs01/pyxterm.js"
),
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("-p", "--port", default=5000, help="port to run server on")
parser.add_argument(
"--host",
default="127.0.0.1",
help="host to run server on (use 0.0.0.0 to allow access from other hosts)",
)
parser.add_argument("--debug", action="store_true", help="debug the server")
parser.add_argument("--version", action="store_true", help="print version and exit")
parser.add_argument(
"--command", default="bash", help="Command to run in the terminal"
)
parser.add_argument(
"--cmd-args",
default="",
help="arguments to pass to command (i.e. --cmd-args='arg1 arg2 --flag')",
)
args = parser.parse_args()
if args.version:
print(__version__)
exit(0)
app.config["cmd"] = [args.command] + shlex.split(args.cmd_args)
green = "\033[92m"
end = "\033[0m"
log_format = green + "pyxtermjs > " + end + "%(levelname)s (%(funcName)s:%(lineno)s) %(message)s"
logging.basicConfig(
format=log_format,
stream=sys.stdout,
level=logging.DEBUG if args.debug else logging.INFO,
)
logging.info(f"serving on http://{args.host}:{args.port}")
debug = args.debug
debug = True
socketio.run(app, debug=debug, port=args.port, host=args.host, allow_unsafe_werkzeug=True )
if __name__ == "__main__":
main()
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap demo</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>
<body>
<h1>Hello, world!</h1>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<div class="accordion" id="accordionPanelsStayOpenExample">
<div class="accordion-item">
<h2 class="accordion-header" id="panelsStayOpen-headingOne">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseOne" aria-expanded="true" aria-controls="panelsStayOpen-collapseOne">
Accordion Item #1 <span class="glyphicon glyphicon-star" aria-hidden="true"> das sdafsdf</span> Star
</button>
</h2>
<div id="panelsStayOpen-collapseOne" class="accordion-collapse collapse show" aria-labelledby="panelsStayOpen-headingOne">
<div class="accordion-body">
<strong>This is the first item's accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
<div class="accordion" id="accordionPanelsStayOpenExample2">
<div class="accordion-item">
<h2 class="accordion-header" id="panelsStayOpen-headingOne2">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseOne2" aria-expanded="true" aria-controls="panelsStayOpen-collapseOne">
Accordion Item #1
</button>
</h2>
<div id="panelsStayOpen-collapseOne2" class="accordion-collapse collapse show" aria-labelledby="panelsStayOpen-headingOne">
<div class="accordion-body">
<strong>This is the first item's accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="panelsStayOpen-headingTwo">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseTwo" aria-expanded="false" aria-controls="panelsStayOpen-collapseTwo">
Accordion Item #2
</button>
</h2>
<div id="panelsStayOpen-collapseTwo" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingTwo">
<div class="accordion-body">
<strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="panelsStayOpen-headingThree">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseThree" aria-expanded="false" aria-controls="panelsStayOpen-collapseThree">
Accordion Item #3
</button>
</h2>
<div id="panelsStayOpen-collapseThree" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingThree">
<div class="accordion-body">
<strong>This is the third item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
</div>
</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
<html lang="en">
<head>
<meta charset="utf-8" />
<title>pyxterm.js</title>
<style>
html {
font-family: arial;
}
</style>
<link
rel="stylesheet"
href="https://unpkg.com/xterm@4.11.0/css/xterm.css"
/>
</head>
<body>
<span style="font-size: 1.4em">pyxterm.js</span>&nbsp;&nbsp;&nbsp;
<span style="font-size: small"
>status:
<span style="font-size: small" id="status">connecting...</span></span
>
<div style="width: 100%; height: calc(100% - 50px)" id="terminal"></div>
<div style="width: 50%; height: calc(20%)" id="term2">another terminal</div>
<p style="text-align: right; font-size: small">
built by <a href="https://chadsmith.dev">Chad Smith</a>
<a href="https://github.com/cs01">GitHub</a>
</p>
<!-- xterm -->
<script src="https://unpkg.com/xterm@4.11.0/lib/xterm.js"></script>
<script src="https://unpkg.com/xterm-addon-fit@0.5.0/lib/xterm-addon-fit.js"></script>
<script src="https://unpkg.com/xterm-addon-web-links@0.4.0/lib/xterm-addon-web-links.js"></script>
<script src="https://unpkg.com/xterm-addon-search@0.8.0/lib/xterm-addon-sear
ch.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js"></script>
<script>
const term = new Terminal({
cursorBlink: true,
macOptionIsMeta: true,
scrollback: 300,
});
// https://github.com/xtermjs/xterm.js/issues/2941
const fit = new FitAddon.FitAddon();
term.loadAddon(fit);
term.loadAddon(new WebLinksAddon.WebLinksAddon());
term.loadAddon(new SearchAddon.SearchAddon());
term.open(document.getElementById("terminal"));
fit.fit();
term.resize(15, 50);
console.log(`size: ${term.cols} columns, ${term.rows} rows`);
fit.fit();
term.writeln("Welcome to pyxterm.js!");
term.writeln("https://github.com/cs01/pyxterm.js");
term.onData((data) => {
console.log("key pressed in browser:", data);
socket.emit("pty-input", { input: data });
});
const socket = io.connect("/pty");
const status = document.getElementById("status");
socket.on("pty-output", function (data) {
console.log("new output received from server:", data.output);
term.write(data.output);
});
socket.on("connect", () => {
fitToscreen();
status.innerHTML =
'<span style="background-color: lightgreen;">connected</span>';
});
socket.on("disconnect", () => {
status.innerHTML =
'<span style="background-color: #ff8383;">disconnected</span>';
});
function fitToscreen() {
fit.fit();
const dims = { cols: term.cols, rows: term.rows };
console.log("sending new dimensions to server's pty", dims);
socket.emit("resize", dims);
}
function debounce(func, wait_ms) {
let timeout;
return function (...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait_ms);
};
}
const wait_ms = 50;
window.onresize = debounce(fitToscreen, wait_ms);
</script>
<script>
const term2 = new Terminal({
cursorBlink: true,
macOptionIsMeta: true,
scrollback: true,
});
// https://github.com/xtermjs/xterm.js/issues/2941
const fit2 = new FitAddon.FitAddon();
term2.loadAddon(fit2);
term2.loadAddon(new WebLinksAddon.WebLinksAddon());
term2.loadAddon(new SearchAddon.SearchAddon());
term2.open(document.getElementById("term2"));
fit2.fit();
term2.resize(15, 50);
console.log(`size: ${term.cols} columns, ${term.rows} rows`);
fit2.fit();
term2.writeln("Welcome to pyxterm.js!");
term2.writeln("https://github.com/cs01/pyxterm.js");
</script>
</body>
</html>
\ No newline at end of file
<html lang="en">
<head>
<meta charset="utf-8" />
<title>pyxterm.js</title>
<style>
html {
font-family: arial;
}
</style>
<link
rel="stylesheet"
href="https://unpkg.com/xterm@4.11.0/css/xterm.css"
/>
</head>
<body>
<span style="font-size: 1.4em">pyxterm.js</span>&nbsp;&nbsp;&nbsp;
<span style="font-size: small"
>status:
<span style="font-size: small" id="status">connecting...</span></span
>
<div style="width: 100%; height: calc(100% - 50px)" id="terminal"></div>
<p style="text-align: right; font-size: small">
built by <a href="https://chadsmith.dev">Chad Smith</a>
<a href="https://github.com/cs01">GitHub</a>
</p>
<!-- xterm -->
<script src="https://unpkg.com/xterm@4.11.0/lib/xterm.js"></script>
<script src="https://unpkg.com/xterm-addon-fit@0.5.0/lib/xterm-addon-fit.js"></script>
<script src="https://unpkg.com/xterm-addon-web-links@0.4.0/lib/xterm-addon-web-links.js"></script>
<script src="https://unpkg.com/xterm-addon-search@0.8.0/lib/xterm-addon-sear
ch.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js"></script>
<script>
const term = new Terminal({
cursorBlink: true,
macOptionIsMeta: true,
scrollback: true,
});
// https://github.com/xtermjs/xterm.js/issues/2941
const fit = new FitAddon.FitAddon();
term.loadAddon(fit);
term.loadAddon(new WebLinksAddon.WebLinksAddon());
term.loadAddon(new SearchAddon.SearchAddon());
term.open(document.getElementById("terminal"));
fit.fit();
term.resize(15, 50);
console.log(`size: ${term.cols} columns, ${term.rows} rows`);
fit.fit();
term.writeln("Welcome to pyxterm.js!");
term.writeln("https://github.com/cs01/pyxterm.js");
term.onData((data) => {
console.log("key pressed in browser:", data);
socket.emit("pty-input", { input: data });
});
const socket = io.connect("/pty");
const status = document.getElementById("status");
socket.on("pty-output", function (data) {
console.log("new output received from server:", data.output);
term.write(data.output);
});
socket.on("connect", () => {
fitToscreen();
status.innerHTML =
'<span style="background-color: lightgreen;">connected</span>';
});
socket.on("disconnect", () => {
status.innerHTML =
'<span style="background-color: #ff8383;">disconnected</span>';
});
function fitToscreen() {
fit.fit();
const dims = { cols: term.cols, rows: term.rows };
console.log("sending new dimensions to server's pty", dims);
socket.emit("resize", dims);
}
function debounce(func, wait_ms) {
let timeout;
return function (...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait_ms);
};
}
const wait_ms = 50;
window.onresize = debounce(fitToscreen, wait_ms);
</script>
</body>
</html>
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment