2016-02-25 28 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