简体   繁体   English

如何将 stdout.read() 保存在 csv 文件中?

[英]How to save stdout.read() in a csv file?

Guys I am struggling to figure out how to save output of a command I ran to a csv file.伙计们,我正在努力弄清楚如何将我运行到 csv 文件的命令的输出保存。 Here is the code i have written so far to get the output from a linux host using paramiko modue.这是我到目前为止编写的代码,用于使用 paramiko 模块从 linux 主机获取输出。

ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip,port=22,username=user_name,password=passwd)
stdin, stdout, stderr = ssh_client.exec_command("some random command")
output = (stdout.read().decode(encoding='ascii'))
print(output)

This is the output I get:这是我得到的输出:

Lun VV_WWN                           VVName                   HostName     
1 600525465446418gsdhgdfhahf14488454 HOST-California_westcos domain123
9 600525465446418gsdhgdfhahf14488454 HOST-Texas_westcos      domain123
4 600525465446418gsdhgdfhahf14488454 HOST-Kasnsas_westcos    domain123
4 600525465446418gsdhgdfhahf14488454 HOST-Ohio_westcos       domain123
7 600525465446418gsdhgdfhahf14488454 HOST-Nevada_westcos     domain123
---------------------------------------------------------------------------
5                                                  total

I need to remove header and footer and save this file as CSV.我需要删除页眉和页脚并将此文件另存为 CSV。 Any suggestion on how can i achieve this.关于如何实现这一目标的任何建议。 I would really appreciate the help.我真的很感激你的帮助。

You can use the csv builtin python package.您可以使用 csv 内置 python 包。

just add the following code:只需添加以下代码:

import csv

lines = list(output.splitlines())
lines = lines[1:-2]

with open('my_csv.csv', 'w', newline='') as csvfile:
    my_writer = csv.writer(csvfile, delimiter=' ')
    for line in lines:
        my_writer.writerow(line[0].split())

good luck and let me know if you need more help.祝你好运,如果您需要更多帮助,请告诉我。 Some reference can be found here: CSV File Reading and Writing可以在这里找到一些参考: CSV File Reading and Writing

This worked for me这对我有用

import csv
split = output.split('\n')
keep = split[1:-3]
word_split = [k.split() for k in keep]
with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(word_split)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM