Monday, September 3, 2012

Screenshotting /dev/vcs

If you ever wanted to know how to take a "screenshot" of a VCS (where your login prompt is displayed) you can use the following snippet:
cat ../tests/igor/libs/common/vcs.py 
#!/bin/env python
#
# bash only:
# su -c 'cat /dev/vcs3 | fold -w $(stty size | cut -d " " -f 2) > /tmp/term'
#


import Image, ImageDraw
import subprocess
import argparse
import sys


def execute(cmd):
    proc = subprocess.Popen(cmd, shell=True, \
                            stdout=subprocess.PIPE, \
                            stderr=subprocess.STDOUT)
    (stdout, stderr) = proc.communicate()
    proc.wait()
    return str(stdout)

def get_size_of_tty(n):
    """Return the number of rows and cols of tty n
    """
    cmd = "stty -F /dev/tty%d size" % n
    rows, cols = execute(cmd).split(" ")
    return (int(rows), int(cols))

def capture_vcs(n, fold_at):
    """Return the contents of vcs n
    Thsi can also be used with (bash) fold -w
    """
    tty = "/dev/vcs%d" % n
    cmd = "cat %s | fold -w %d" % (tty, fold_at)
    return execute(cmd)

def image_from_vcs(n, stridex=6, stridey=12):
    """Create an image from vcs n
    """
    height, width = get_size_of_tty(n)
    im = Image.new(Image.MODES[6], (width * stridex, height * stridey))
    draw = ImageDraw.Draw(im)
    nl = 0
    screen = capture_vcs(n, fold_at=width)
    for line in screen.split("\n"):
        draw.text((0, stridey * nl), line)
        nl += 1
    return im

def screenshot_from_vcs(n, filename, format="png"):
    """Create a screenshot of a vcs and write it to a file
    """
    im = image_from_vcs(args.vcs)
    im.save(open(filename, "wb"), format.upper())

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Create a screenshot from ' +
                                                 'a console.')
    parser.add_argument('vcs', type=int,
                        help='The VCS/TTY to be captured')
    parser.add_argument('--format', metavar='t', type=str,
                        choices=['png'], default="png",
                        help='The image format')
    parser.add_argument('file', metavar='dst', type=str,
                        help='The destination file')
    args = parser.parse_args()
    screenshot_from_vcs(args.file, args.format.upper())
The images can be used to create a screen capture of your console.

No comments:

Post a Comment