Search code examples
pythonlinuxscriptingautomationrecording

Script to capture everything on screen


So I have this python3 script that does a lot of automated testing for me, it takes roughly 20 minutes to run, and some user interaction is required. It also uses paramiko to ssh to a remote host for a separate test.

Eventually, I would like to hand this script over to the rest of my team however, it has one feature missing: evidence collection!

I need to capture everything that appears on the terminal to a file. I have been experimenting with the Linux command 'script'. However, I cannot find an automated method of starting script, and executing the script.

I have a command in /usr/bin/

script log_name;python3.5 /home/centos/scripts/test.py

When I run my command, it just stalls. Any help would be greatly appreciated!

Thanks :)


Solution

  • I actually managed to do it in python3, took a lot of work, but here is the python solution:

    def record_log(output):
    try:
        with open(LOG_RUN_OUTPUT, 'a') as file:
            file.write(output)
    except:
        with open(LOG_RUN_OUTPUT, 'w') as file:
            file.write(output)
    
    
    def execute(cmd, store=True):
    proc = Popen(cmd.encode("utf8"), shell=True, stdout=PIPE, stderr=PIPE)
    output = "\n".join((out.decode()for out in proc.communicate()))
    template = '''Command:\n====================\n%s\nResult:\n====================\n%s'''
    output = template % (cmd, output)
    print(output)
    if store:
        record_log(output)
    return output
    
    
    # SSH function
    def ssh_connect(start_message, host_id, user_name, key, stage_commands):
    print(start_message)
    try:
        ssh.connect(hostname=host_id, username=user_name, key_filename=key, timeout=120)
    except:
        print("Failed to connect to " + host_id)
    for command in stage_commands:
        try:
            ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(command)
        except:
            input("Paused, because " + command + " failed to run.\n  Please verify and press enter to continue.")
        else:
            template = '''Command:\n====================\n%s\nResult:\n====================\n%s'''
            output = ssh_stderr.read() + ssh_stdout.read()
            output = template % (command, output)
            record_log(output)
            print(output)