2016-02-25 22 views
0

所以我有这个python3脚本为我做了很多自动化测试,大概需要20分钟才能运行,并且需要一些用户交互。它还使用paramiko ssh到远程主机进行单独测试。脚本捕获屏幕上的所有内容

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

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

我在/ usr/bin中有一个命令/

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

当我运行我的命令,它只是个摊位。任何帮助将不胜感激!

谢谢:)

回答

1

我实际上设法做到在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) 
2

是输出重定向到一个文件,你需要什么?

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

或者,如果你想保持在终端上的输出,并保存到一个文件:

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

我需要做到这一点,并结束了与联合pexpectttyrec的解决方案。

ttyrec产生的输出文件可以用一些不同的播放器应用程序播放 - 我使用TermTVIPBT

如果没记错,我不得不使用Pexpect的推出ttyrec(以及我测试的其它命令),因为我是用詹金斯来安排我的测试的执行,并Pexpect的似乎是获得工作的最简单方法Jenkins工作中的交互式shell。

在您的情况可能会得以脱身,只要使用ttyrec,并跳过Pexpect的一步 - 尝试运行ttyrec -e command如ttyrec文档提及。

最后,关于交互式shell的主题,还有一个名为“empty”的替代品,我也取得了一些成功 - 请参阅http://empty.sourceforge.net/。如果你正在运行Ubuntu或Debian的你可以用apt-get install empty-expect