![](/img/trans.png)
[英]SSH into a server, run a command and save its output to a variable in Python
[英]Python - save SSH command output to CSV
我正在嘗試將使用Paramiko模塊運行的SSH命令的輸出保存在CSV文件中。 但是輸出以錯誤的格式保存。 例如,每個字母在單獨的列中,所有內容都顯示在1行中。
獲取命令並將其寫入CSV的Python代碼的一部分。
stdin,stdout,stderr = ssh.exec_command("lastlog")
temp = ""
for line in stdout.readlines():
print line.strip()
temp = temp + line
# Open a file and write the output to it
with open('output.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(temp)
print line.strip()
輸出格式如下: 命令輸出
有人可以告訴我我在做什么錯嗎?
您的代碼肯定會丟失新行。
應該這樣做:
stdin, stdout, stderr = ssh.exec_command("lastlog")
with open('output.csv', 'wb') as f:
shutil.copyfileobj(stdout, f)
我不確定“單獨欄中的每個字母” 。
這是我得到的最好的。 也許有更好的方法可以做到這一點,但至少可以解決目的。
stdin, stdout, stderr = ssh.exec_command("lastlog | awk \'{if (NF==4)print$1\",,,\"$2\" \"$3\" \"$4; if (NF==8) print $1\",\"$2\",,\"$3\" \"$4\" \"$5\"\"$6\" \"$7\" \"$8;if (NF==9) print $1\",\"$2\",\"$3\",\"$4\" \"$5""$6\" \"$7\" \"$8\" \"$9}\'")
log_output = stdout.readlines()
log_output_clean = [i.strip("\n").split(",") for i in log_output[1:]] # First row did not parse well,so ignored it
log_output_clean.insert(0, ['Username', 'Port', 'From', 'Latest']) # Adding header row
with open('log_output.csv', 'w') as output_fn:
wr = csv.writer(output_fn)
wr.writerows(log_output_clean)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.