-1

I'm working on script that checks on ping from several groups of devices and writing the devices ip to text file when the ping is successful

import os

ip_list=[]
data = open("data.txt",'w')

def pngtest():
    g=4
    s=2
    e=106
    while g < 11:
        for ip in range(s,e):
            ip_list.append('10.0.'+str(g)+'.'+str(ip))
        if g == 8:
            s=5
            e=122
        elif g == 9:
            s=2
            e=198
        elif g == 10:
            s=2
            e=254
        else:
            s=2
            e=106
        g +=1
pngtest()

for ip in ip_list:
    response = os.popen(f"ping {ip}").read()
    if "Received = 4" in response and 'TTL' in response:
        data.write(f"{ip}")
    else:
        print(f"ping {ip} failed")
data.close()

the problem is that it seems that the script does not writing any data to the text file. how do I fix this?

Gnugget
  • 11
  • 2
  • 2
    This if statement is never true in your code, probably: `if "Received = 4" in response and 'TTL' in response:` – oskros May 31 '21 at 07:09
  • 1
    Are you sure the data is written, then deleted or could it be never written at all – mousetail May 31 '21 at 07:13
  • 1
    try using 'a' mode instead of 'w' in the `open` function https://docs.python.org/3/library/functions.html#open – py_dude May 31 '21 at 07:29

2 Answers2

0

try adding a timeout to ping

response = os.popen(f"ping -t 4 {ip}").read()

also print the response to see why you if didn't work.

print(f"ping {ip} failed response={response}")
Yoav Glazner
  • 7,936
  • 1
  • 19
  • 36
0

Try this. ping -c 1 will stop sending packets after single request.

for ip in ip_list:
  print("Checking" + IP)
  response = os.system("ping -c 1 " + ip + "> /dev/null" )
  if response == 0:
    data.write(f"{ip}")
  else:
    print(f"ping {ip} failed")

Maybe you should reframe your question. It is similar to this post.

Nannigalaxy
  • 492
  • 6
  • 17