我一直在尝试执行NSLOOKUP并将值写入csv文件。
我的file1.csv:
Hostname
abc1
def2
fgh3
.
.
.
and so on
我想对这些主机名进行nslookup,并将FQDN写入file2.csv,如下所示:
Hostname FQDN
abc1 abc1.na.edu
def2 bcd2.sa.edu
fgh3 fgh3.ea.edu
.
.
and so on
这是我的代码:
import socket
import csv
name = []
with open('file1.csv', 'r', newline='') as csvinput:
reader = csv.reader(csvinput)
for line in csvinput:
name = socket.getfqdn(line)
with open('file2.csv', 'w', newline='') as csvoutput:
fieldnames = (['Hostname', 'FQDN'])
output = csv.writer(csvoutput)
output.writerow(fieldnames)
output.writerow([name])
我只能在输出文件中获得一个随机主机名的fqdn。虽然,当我只使用' print(name)'它为我提供了控制台中的所有FQDN。我知道我错过了什么,请帮助!!
在代码中进行了一些更改:
import socket
import os
import csv
name = {}
CI = {}
with open('file1.csv', 'r', newline='') as csvinput:
reader = csv.DictReader(csvinput)
# status = [row['FQDN'] for row in rows]
for rows in reader:
CI = rows['CI_Name']
name = socket.getfqdn(CI)
with open('file2.csv', 'a', newline='') as csvoutput:
output = csv.writer(csvoutput)
#fieldnames = ['CI_Name', 'FQDN']
#output = csv.DictWriter(csvoutput, fieldnames=fieldnames)
#output.writerow(rows)
output.writerows([[CI] + [name]])
我可以打印名称和相应的FQDN,但无法在csv列上打印标题,即' CI_Name'和' FQDN'
答案 0 :(得分:0)
import socket
import os
import csv
name = {}
CI = {}
with open('file1.csv', 'r', newline='') as csvinput:
reader = csv.DictReader(csvinput)
# status = [row['FQDN'] for row in rows]
with open('file2.csv', 'w', newline='') as csvoutput:
fieldnames = ['CI_Name', 'FQDN']
output = csv.DictWriter(csvoutput, fieldnames=fieldnames)
output.writeheader()
for rows in reader:
CI = rows['CI_Name']
name = socket.getfqdn(CI)
with open('file2.csv', 'a', newline='') as csvoutput:
output = csv.writer(csvoutput)
output.writerows([[CI] + [name]])