我目前正在尝试弄清楚如何在python中创建一个CSV文件,它将通过SSH列出/ logs类别的所有文件以及服务器名称。 问题是,每当我开始编写脚本时,我都会得到类似的内容:
server, machine
IP;file1 file2, file3 file4 etc
IP2;file1 file2, file3, file 4 etc.
在我的CSV中,我需要这样的东西:
server, machine
IP;file1
IP;file2
Ip;file3
IP;file4
IP2;file1
IP2;file2
IP2;file3
etc...
使用我当前的代码,我不知道如何从这个问题开始 相关片段如下所示:
SLIST = path to csv from which i took IP
CMD2 = 'ssh %s ls /opt/syslog/logs'
def mloop():
f = open('out.csv', 'a')
columnTitleRow = "server, machine\n"
f.write(columnTitleRow)
for i in csv2hash(SLIST):
if i.get('IP'):
r = getoutput(CMD2 % (i['IP']))
server = i['IP']
machine = r
row = server + ";" + machine + ";" + "\n"
f.write(row)
f.close()
正如你所看到的......“r”从logs文件夹获取所有文件,问题是我不知道如何将每个文件分别放到csv。
答案 0 :(得分:0)
使用python in-build library csv
import csv
output_file = open('outputfile.csv', 'wb')
fieldnames = ['server', 'machine']
writer = csv.DictWriter(output_file, fieldnames=fieldnames)
writer.writeheader()
def mloop():
...
...
server = i['IP']
machine = r
row = {'server': server, 'machine': machine}
writer.writerow(row)
output_file.close()
详细了解Python csv