I'm unable to find any good easy to learn documentation on python and networking. In this instance, I'm just trying to make a easy script which I can ping a number of remote machines.
for ping in range(1,10):
ip="127.0.0."+str(ping)
os.system("ping -c 3 %s" % ip)
A simple script like that will ping the machines fine, but I'd like to get the script to returns 'active' 'no response' Which makes me think I'll have to look up the time module as well, I think time.sleep(5)
and after that, there would be a break statement. Which makes me think there should be a while loop inside for. I'm not 100% sure, I could be going in the wrong direction completely :/ if anyone could help or point me in the direction of some documentation that'd be great.
Try
subprocess.call
. It saves the return value of the program that was used.According to my ping manual, it returns 0 on success, 2 when pings were sent but no reply was received and any other value indicates an error.
Python actually has a really sweet method that will 'return an iterator over the usable hosts in the network'. (setting strict to false iterates over all IPs)
For example:
The wait interval (-i0.1) may be important for automations, even a one second timeout (-t1) can take forever over a .0/24
EDIT: So, in order to track ICMP (ping) requests, we can do something like this:
Which will return something like:
i.e. all of the IPs responding to ICMP ranging over an entire /23-- Pretty cool!
This script:
will produce something like this output:
You can capture the output if you replace
limbo
withsubprocess.PIPE
and usecommunicate()
on thePopen
object:This way you get the return value of the command and can capture the text. Following the manual this is the preferred way to operate a subprocess if you need flexibility:
Thank you so much for this. I have modified it to work with Windows. I have also put a low timeout so, the IP's that have no return will not sit and wait for 5 seconds each. This is from hochl source code.
Just change the ip= for your scheme and the xrange for the hosts.
I'm a beginner and wrote a script to ping multiple hosts.To ping multiple host you can use ipaddress module.