捕获屏幕上所有内容的脚本

Script to capture everything on screen

所以我有这个 python3 脚本,它为我做了很多自动化测试,运行 大约需要 20 分钟,并且需要一些用户交互。它还使用 paramiko 通过 ssh 连接到远程主机以进行单独测试。

最后,我想把这个脚本交给我团队的其他成员,但是,它缺少一个功能:证据收集!

我需要将出现在终端上的所有内容捕获到一个文件中。我一直在试验 Linux 命令 'script'。但是,我找不到启动脚本和执行脚本的自动化方法。

我在/usr/bin/

中有一个命令
script log_name;python3.5 /home/centos/scripts/test.py

当我 运行 我的命令时,它只是停止了。任何帮助将不胜感激!

谢谢:)

您需要将输出重定向到文件吗?

python3.5 /home/centos/scripts/test.py > output.log 2>&1

或者,如果您想将输出保留在终端上并将其保存到文件中:

python3.5 /home/centos/scripts/test.py 2>&1 | tee output.log

我需要这样做,最终得到了一个结合 pexpect and ttyrec.

的解决方案

ttyrec 生成可以用几个不同的播放器应用程序播放的输出文件 - 我使用 TermTV and IPBT.

如果没记错的话,我不得不使用 pexpect 来启动 ttyrec(以及我测试的其他命令),因为我使用 Jenkins 来安排我的测试的执行,而 pexpect 似乎是获得一个最简单的方法在 Jenkins 作业中进行交互式工作 shell。

在您的情况下,您可以仅使用 ttyrec 并跳过预期步骤 - 尝试 运行 ttyrec -e command,如 ttyrec 文档中所述。

最后,关于交互式 shell 的主题,有一个名为 "empty" 的 pexpect 替代方案,我也取得了一些成功 - 请参阅 http://empty.sourceforge.net/。如果您是 运行 Ubuntu 或 Debian,您可以使用 apt-get install empty-expect

安装空的

我实际上在 python3 中做到了,花了很多功夫,但这是 python 解决方案:

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)