Avatar of adbyits
adbyits
 asked on

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")
Operating SystemsNetworkingPython

Avatar of undefined
Last Comment
noci

8/22/2022 - Mon
noci

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.
adbyits

ASKER
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
noci

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.
Your help has saved me hundreds of hours of internet surfing.
fblack61
adbyits

ASKER
you are great thank you
adbyits

ASKER
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
ASKER CERTIFIED SOLUTION
noci

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
adbyits

ASKER
Thank you so much just what i needed to the nextg step now :) a
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
adbyits

ASKER
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
noci

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

And it should clear up.
adbyits

ASKER
try:
                hostname = ""
                aliases = ""
                ipaddrs = ""
                int: (hostname, aliases, ipaddrs)  = socket.gethostbyaddr(ip)
                #hostname = socket.gethostbyaddr(ip)
                print(hostname)
                print('"{}",{},"ONLINE"'.format( hostname,ip), file=f)
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
noci

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:?
adbyits

ASKER
i am in silly bugger so sorry for wasting you time
noci

no problem...
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.