0

Beginner with a beginner question: I am trying to build a python program to ping a csv file of ip addresses.

This script is nearly there, however when I convert the csv data to a list and use the for loop on it... the brackets and quotes remain in the ip address ['10.10.10.1'] which prevents me from pinging.

I know there are numerous ways to remove quotes/brackets from list items, but what would work best here?

I think I am nearly there, what is a simple solution to this?

import os
import csv

csvFile = open('hosts.csv')
csvReader = csv.reader(csvFile)
csvData = list(csvReader)

for ip in csvData:
    response = os.system('ping ' + str(ip))
    if response == 0:
        print(ip, 'is up')
    else:
        print(ip, 'is down')
dmbr
  • 1
  • 4

1 Answers1

2

You're actually embedding a list into a list with the csvData = list(csvReader) line.

csv.reader() returns a list of strings for each row read from the csv file. So if you have multiple lines in your file you'll end up with n-rows of lists.

The first for loop will handle if your file has multiple rows. The second for loop will parse through the list returned by csv.reader().

Also, your ping statement will continue to ping. There are other unexpected issues you may hit but that's for another question.

Try this:

import os
import csv

with open('hosts.csv') as csvfile:
  reader = csv.reader(csvfile)
  for line in reader:
    for ip in line:
      response = os.system('ping -c 1 ' + str(ip))
      if response == 0:
        print (ip, ' is up')
      else:
        print (ip, ' is down')

References

Python3 CSV
Pinging Servers in Python

kenlukas
  • 3,616
  • 9
  • 25
  • 36