To use ping, we will import os module. To have a little bit of pause between pings, time module is needed.
Variable ip will hold left part of IP address, as a base for full IP.
import os, time
ip = "192.168.0."
To go through all range of IPs for loop is needed (1, 255). Pause is set to 5 seconds between pings.
Results of pinging for every individual ip address will end up in - result. We will send just one packet, no need for 4 of them. It will be too slow.
Secondary for loop is needed to check for "TTL" string in system return. You can see that with normal pinging in terminal or command prompt if you are on Windows.
for x in range(1, 255):
time.sleep(5)
result = os.popen("ping -n 1 " + ip + str(x))
for linija in result.readlines():
if "TTL" in linija:
print("DETECTED: ", linija)
If we are unable to ping IP, that networking device is probably off, so we will just print that.
else:
print("OFF !", ip + str(x))
Full Script:
import os, time
ip = "192.168.0."
for x in range(1, 255):
time.sleep(5)
result = os.popen("ping -n 1 " + ip + str(x))
for linija in result.readlines():
if "TTL" in linija:
print("DETECTED: ", linija)
else:
print("OFF !", ip + str(x))
Learn More:
Free Python Programming Course
Python Examples
Python How To
Python Modules
No comments:
Post a Comment