2016-12-23 149 views
-1

我想將python腳本(sshClient.py)的輸出保存爲CSV文件。你能幫我怎麼做嗎?提前致謝。我在這裏分享的代碼和結果輸出以便您更好地理解。執行python腳本並將輸出保存爲CSV文件

import sys 
import time 
import select 
import paramiko 

host = '169.254.115.1' 
i = 1 

# 
# Try to connect to the host. 
# Retry a few times if it fails. 
# 
while True: 
    print ('Trying to connect to %s (%i/3)' % (host, i)) 

    try: 
     ssh = paramiko.SSHClient() 
     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
     ssh.connect(host, port=22, username='user', password='user') 
     print ("Connected to %s" % host) 
     break 
    except paramiko.AuthenticationException: 
     print ("Authentication failed when connecting to %s") % host 
     sys.exit(1) 
    except: 
     print ("Could not SSH to %s, waiting for it to start" % host) 
     i += 1 
     time.sleep(2) 

    # If we could not connect within time limit 
    if i == 3: 
     print ("Could not connect to %s. Giving up") % host 
     sys.exit(1) 

# Send the command (non-blocking) 
stdin, stdout, stderr = ssh.exec_command("cd /opt/cohda/test; sudo ./runtest_iperf_tx.sh") 

# Wait for the command to terminate 
while not stdout.channel.exit_status_ready(): 
    # Only print data if there is data to read in the channel 
    if stdout.channel.recv_ready(): 
     rl, wl, xl = select.select([stdout.channel], [], [], 0.0) 
     if len(rl) > 0: 
      # Print data from stdout 
      print (stdout.channel.recv(1024)), 
# 
# Disconnect from the host 
# 
print ("Command done, closing SSH connection") 
ssh.close() 

得到的輸出:Throughput Vs Time

+0

你可以寫'(stdout.channel.recv( 1024))'到一個文件(以二進制模式打開)而不是打印它。 –

+0

你可以編輯我的代碼來顯示一個例子嗎? –

+0

你能像發佈文本那樣發佈幾行輸出嗎? –

回答

-1

沒有測試的事,但這種效果,如果數據是ASCII應該工作...

# Wait for the command to terminate 
csv_str = "" 
while not stdout.channel.exit_status_ready(): 
    # Only print data if there is data to read in the channel 
    if stdout.channel.recv_ready(): 
     rl, wl, xl = select.select([stdout.channel], [], [], 0.0) 
     if len(rl) > 0: 
      # Print data from stdout 
      print (stdout.channel.recv(1024)), 
      csv_str += str.split(str(stdout.channel.recv(1024)),",") 
# 
# Disconnect from the host 
# 
PathFileName = "/hard/path/filename.csv" 
f = open(PathFileName,'a') 
f.write(csv_str) 
f.close() 
+0

感謝您的回覆。需要定義'addrStr',因爲它說未解決的參考。在這種情況下我該怎麼辦? –

+0

對不起... ...我編輯了片段 –

+0

只是一個愚蠢的問題。如果我沒有錯,那麼你使用命令PathFileName =「/hard/path/filename.csv」將文件保存在特定的位置..好嗎? –

相關問題