We help IT Professionals succeed at work.

Write the output of my python ping script to a csv file

I would like to add the results of my ping test in python to a csv file i was hoping someone could please help me with this please as i have been pulling my hair out trying

here the code of my pings

import os
import socket
import csv


iplist = []

#loop from 1 to 255
# Appends the concatenated ip to the ip_list

for ip in range(1,256):
    iplist.append("192.168.1." + str(ip))

#show me the list of ip address in the list

print("*********ADBY IT AND MEDIA SOLUTIONS NETWORK SCAN*********")
# Loop to ping ip_list and check if device up or down
# Outputs to results.txt file
print("Starting ping test")
for ip in iplist:
   
    response = os.popen(f"ping  {ip} -n 1").read()
    if "Received = 4"  and "Approximate" in response:
        try:
            hostname = socket.gethostbyaddr(ip)

            print(" {}ONLINE".format( hostname))
        except socket.error:
            hostname = "No HOST NAME "

            print(" {}{} ONLINE".format( hostname,ip))



       
        #print({hostname} +  "The System is online")
    #else:
       # print(f"{ip} OFFLINE")
Comment
Watch Question

nociSoftware Engineer
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
changing print statement to:     print("{},{},ONLINE".format(host,ip)) # for on-line
and  to: print(",{},OFFLINE".format(ip))     # for off-line
and print a optional header row first: print('"host","ip","status"')   #(before any loop)
 
and running the program with:   python myping.py >results.txt
will do.

Author

Commented:
thats great mate and i am just testing it but i would like to package this and at the end i will be adding a webgui so for all my sites i can see waht is online  is there a way to add it to the code
nociSoftware Engineer
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
If you want monitoring you may want more and other information. Icinga / Nagios  and the like are more useful.
here is adapted code:
import os
import socket
import csv

iplist = []
with open('result.txt', 'w') as f:
 
    #loop from 1 to 254
    # Appends the concatenated ip to the ip_list
    # Outputs to results.txt file

    for ip in range(1,255):
        iplist.append("192.168.1." + str(ip))

    #show me the list of ip address in the list

    print("*********ADBY IT AND MEDIA SOLUTIONS NETWORK SCAN*********")
    print("Starting ping test")
    for ip in iplist:
   
        response = os.popen(f"ping  {ip} -n 1").read()
        if "Received = 4"  and "Approximate" in response:
            try:
                hostname = socket.gethostbyaddr(ip)
                print('"{}",{},"ONLINE"'.format( hostname,ip), file=f)
            except socket.error:
                hostname = "No HOST NAME "
                 print('"{}",{},"ONLINE"'.format( hostname,ip), file=f)
           #print({hostname} +  "The System is online")
        else:
            print(f'"",{},"OFFLINE"'.format(ip), file=f)

Open in new window


Note that this code has issues like nework ranges and is only applicable for a small network and may need adjustments for different networks.

Author

Commented:
you are great thank you

Author

Commented:
sorry to be a bother mate i am getting this errorr with the code

  File ".\ping.py", line 25, in <module>
    print('"{}",{},"ONLINE"'.format( hostname), file=f)
IndexError: Replacement index 1 out of range for positional args tuple
Software Engineer
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
It should be: ...
 print('"{}",{},"ONLINE"'.format( hostname,ip), file=f)

Author

Commented:
Thank you so much just what i needed to the nextg step now :) a

Author

Commented:
One last thing if i can mate sorry for been a pain the CSV looks look but can you tell me if there is a way in the image below you see the name also has the ip address is there a way just to show the name
Capture.PNG
nociSoftware Engineer
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
Change:
 hostname = socket.gethostbyaddr(ip)
into:
 (hostname, aliases, ipaddrs)  = socket.gethostbyaddr(ip)

And it should clear up.

Author

Commented:
try:
                hostname = ""
                aliases = ""
                ipaddrs = ""
                int: (hostname, aliases, ipaddrs)  = socket.gethostbyaddr(ip)
                #hostname = socket.gethostbyaddr(ip)
                print(hostname)
                print('"{}",{},"ONLINE"'.format( hostname,ip), file=f)
nociSoftware Engineer
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
int: does NOT belong there...
one line should be changed into ONE other line

int: was a typo from into:   (belonging to the word Change:...
(you didn;tinclude change: in the code, so why the int:?

Author

Commented:
i am in silly bugger so sorry for wasting you time
nociSoftware Engineer
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
no problem...