#!/usr/bin/env python3 """Type lines into a QEMU guest via the monitor's `sendkey` command. Each positional argument is one line: it is typed character by character (US layout) followed by Enter. Use it to drive the rs-dos shell from a test script without a display. Used by scripts/tests/test-*.sh, and manually against an interactive session started with `./scripts/run.sh --monitor`: ./scripts/tests/sendkeys.py "ls /disk" "date" "poweroff" ./scripts/tests/sendkeys.py --sock /tmp/rsdos-monitor.sock "date" Environment: QMON_SOCK (default: /tmp/rsdos-monitor.sock) """ import os import socket import sys import time SOCK = os.environ.get("QMON_SOCK", "/tmp/rsdos-monitor.sock") # Unshifted punctuation needs QEMU's *named* keys — bare '-'/'.'/'/' are # not valid sendkey names (and '-' is the modifier separator). BASE = { "-": "minus", "=": "equal", "[": "bracketleft", "]": "bracketright", "\\": "backslash", ";": "semicolon", "'": "apostrophe", ",": "comma", ".": "dot", "/": "slash", "`": "grave", } # Characters that need a shift key on US layout, and the key QEMU's # `sendkey` understands for them. SHIFT = { "~": "grave", "!": "1", "@": "2", "#": "3", "$": "4", "%": "5", "^": "6", "&": "7", "*": "8", "(": "9", ")": "0", "_": "minus", "+": "equal", "{": "bracketleft", "}": "bracketright", "|": "backslash", ":": "semicolon", '"': "apostrophe", "<": "comma", ">": "dot", "?": "slash", } ALNUM = set("abcdefghijklmnopqrstuvwxyz0123456789") def connect(path, timeout=60): """Connect to the monitor socket, retrying until QEMU is up.""" deadline = time.time() + timeout while True: try: s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect(path) return s except OSError: if time.time() > deadline: raise time.sleep(0.2) def sendkey(sock, keys): sock.sendall(("sendkey %s\n" % keys).encode()) def type_line(sock, line): for ch in line: if ch == " ": sendkey(sock, "spc") elif ch in BASE: sendkey(sock, BASE[ch]) elif ch in SHIFT: sendkey(sock, "shift-" + SHIFT[ch]) elif ch.isupper(): sendkey(sock, "shift-" + ch.lower()) elif ch in ALNUM: sendkey(sock, ch) else: sys.stderr.write("warning: no sendkey mapping for %r\n" % ch) continue time.sleep(0.25) sendkey(sock, "ret") time.sleep(1.5) def main(): args = [a for a in sys.argv[1:] if a != "--sock"] sock_path = SOCK if "--sock" in sys.argv: i = sys.argv.index("--sock") sock_path = sys.argv[i + 1] args = sys.argv[i + 2:] if not args: sys.stderr.write(__doc__ or "") return 1 sock = connect(sock_path) # Let the monitor drain any startup banner before typing. time.sleep(0.5) for line in args: try: type_line(sock, line) except OSError: # Guest powered off (last line was usually "poweroff"). break return 0 if __name__ == "__main__": sys.exit(main())