1

Ping_Python Below is Code to ping hosts and create a CSV file out of the results.

import os
for i in range (0,255):
    for j in range(1,254):
        hostname = "10.222.{0}.{1}".format(i,j)
        response = os.system ("ping -n 1 " + hostname)
        if response == 0:
            fp = open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'w')
            fp.writelines(hostname + "host up\n")

        else:
            fp = open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'w')
            fp.write(hostname + "host dead\n")

This code allows me to ping hosts,but while writing the results to a CSV, it overwrites the previously written result and only writes penultimate or unltimate result.

leo
  • 8,106
  • 7
  • 48
  • 80

1 Answers1

2

Change both of

fp = open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'w')

to

fp = open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'a')

in order to open the file in append mode.

You can also improve your code by using with, so you don't open the file every iteration:

import os

with open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'a') as fp:
    for i in range (0,255):
        for j in range(1,254):
            hostname = "10.222.{0}.{1}".format(i,j)
            response = os.system ("ping -n 1 " + hostname)
            if response == 0:
                fp.writelines(hostname + "host up\n")
            else:
                fp.write(hostname + "host dead\n")

This will also have the benefit of closing the file when the script ends.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • Hi Deepspace, Fixed the code with this correction, added the line below after "import os", opened the file globally. **fp = open(r"C:\Users\anudeepa\Desktop\Work\Bala\xyz.csv", 'w')** ` –  May 23 '16 at 07:43