Python - 将 SSH 命令输出保存到 CSV
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()
的输出格式如下:
Command Output
有人可以告诉我我做错了什么吗?
您的代码肯定会丢失新行。
应该这样做:
stdin, stdout, stderr = ssh.exec_command("lastlog")
with open('output.csv', 'wb') as f:
shutil.copyfileobj(stdout, f)
我不确定 "every letter in a separate column"。
这是我得到的最好的。可能有更好的方法来做到这一点,但至少这解决了目的。
stdin, stdout, stderr = ssh.exec_command("lastlog | awk \'{if (NF==4)print\",,,\"\" \"\" \"; if (NF==8) print \",\"\",,\"\" \"\" \"\"\"\" \"\" \";if (NF==9) print \",\"\",\"\",\"\" \"""\" \"\" \"\" \"}\'")
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)
我正在尝试使用 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()
的输出格式如下:
Command Output
有人可以告诉我我做错了什么吗?
您的代码肯定会丢失新行。
应该这样做:
stdin, stdout, stderr = ssh.exec_command("lastlog")
with open('output.csv', 'wb') as f:
shutil.copyfileobj(stdout, f)
我不确定 "every letter in a separate column"。
这是我得到的最好的。可能有更好的方法来做到这一点,但至少这解决了目的。
stdin, stdout, stderr = ssh.exec_command("lastlog | awk \'{if (NF==4)print\",,,\"\" \"\" \"; if (NF==8) print \",\"\",,\"\" \"\" \"\"\"\" \"\" \";if (NF==9) print \",\"\",\"\",\"\" \"""\" \"\" \"\" \"}\'")
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)