0

I am a fresher when it comes to Programming and my current work requires me to write a python script to continously ping a set of hosts and save the result to a CSV file with timestamps.

So my CSV file should fill up with logs when the host is down which i am tracking through "Request timed out"

import os
results_file = open("results.txt","w")
ip_list = []
len(ip_list)

for ip in range(1,11):
    ip_list.append("10.100."+ str(ip)+ ".1")

len(ip_list)

for ip in ip_list:
    response = os.popen(f"ping {ip} -t").read() 
    print(response)
    if "Request timed out" in response:
        results_file.write(f"DOWN {ip} Connection Unsuccessful" + "\n")
    else:
        results_file.write(f"Works fine" + "\n")

I managed to figure out how to ping hosts and check if they are UP of DOWN. But continous ping does not fetch any result.

What Can i Do?

1
  • What do you mean by continuous? You loop over the IPs and check only once. You need a while loop (probably with some sleep inside) or a scheduler to do it "continuously". Commented Dec 15, 2022 at 8:42

1 Answer 1

1

This works but im not sure what you intended with -t.
I used -c so that it sends only 1 request.

for ip in ip_list:
    response = os.system(f"ping -c 1 {ip}")
    print(response)
    if response != 0:
        results_file.write(f"DOWN {ip} Connection Unsuccessful" + "\n")
    else:
        results_file.write(f"Works fine" + "\n")
Sign up to request clarification or add additional context in comments.

2 Comments

Yea it works when i use -c or -n. But i need to monitor the ping constantly. Generally -t is the command we give on the cmd to let it ping continously. My script needs to alert me when it hits a timeout.
Just put a while loop over the for loop. With -t you just dont let it get a response because it does not finish the response. @kalpanaramesh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.