如何使用Python从csv Ping测试100台设备?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (133)

我正在尝试导入一个具有主机名的csv文件,并对这样的100个设备进行ping测试。

CSV1:

Hostname  
abc  
bcd  
efg  
.  
.  
and so on

我想要执行ping测试,并在输出csv文件中写入ping状态(无论是UP还是DOWN)以及相应的主机名。

像这样的东西:

输出:

Hostname  Ping Status  
abc  UP  
bcd  DOWN  
efg  DOWN  
.  .  
.  .  
and so on

import os
import csv

with open('CSV1.csv', 'r') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

hosts = [row['CI_Name'] for row in rows]
statuses = [row['Status'] for row in rows]

for row in rows:
    #ping hosts
    hostname = row['CI_Name']
    response = os.system("ping -n 1 " + hostname)
    print ("[DEBUG]", response)
    if response == 0:
        print (hostname, 'is up')
        row['Status'] = 'Up'
    else:
        print (hostname, 'is down')
        row['Status'] = 'Down'

#write results
with open("Output Final.csv", "w") as w:
    writer = csv.writer(w)

我在Python控制台中获取输出,并显示了与'CMD'完成时相同的ping详细信息。但我的输出csv文件不变。

这是代码的完成版本; 尽管我仍然在为它打印这些设备的IP地址,并在将它写入csv文件时获取正确的标头。

import socket
import os
import csv
name = {}
CI = {}
hostname = {}
status = {}
with open('Output1.csv', 'r', newline='') as csvinput:
    reader = csv.DictReader(csvinput)

    for rows in reader:
        CI = rows['CI_Name']
        name = socket.getfqdn(CI)
        data = name
        hostname = rows['CI_Name']
        response = os.system('ping -n 2 ' + hostname)
        if response == 0:
            status = 'Up'
        else:
            status = 'Down'
        with open('Output Final.csv', 'a', newline='') as csvoutput:
            output = csv.writer(csvoutput)
            output.writerow([hostname] + [data] + [status])
提问于
用户回答回答于
#write results
with open("Output Final.csv", "w", newline='') as w:
    writer = csv.writer(w)
    writer.writerow(["CI_NAME","Status"])
    for r in rows:
        writer.writerow((r['CI_Name'], r['Status']))

扫码关注云+社区

领取腾讯云代金券