Pinging IP Range with Scapy

I am trying to write a Python script that uses the Scapy module to check the internal IP range to determine which IP address is on the network. I still have this:

#!/usr/bin/python from scapy.all import * conf.verb = 0 for ip in range(0, 256): packet = IP(dst="192.168.0." + str(ip), ttl=20)/ICMP() reply = sr1(packet) if "192.168." in reply.src: print reply.src, "is online" 

And the program will sit for a while, doing nothing, and then, if I kill it with CTRL + C, I get an error message:

 Traceback (most recent call last): File "sweep.py", line 7, in <module> if "192.168." in reply.src: AttributeError: 'NoneType' object has no attribute 'src' 

However, if I try to use a single IP address rather than a range, it works. Like this:

 #!/usr/bin/python from scapy.all import * conf.verb = 0 packet = IP(dst="192.168.0.195", ttl=20)/ICMP() reply = sr1(packet) if "192.168." in reply.src: print reply.src, "is online" 

Does anyone know how I can fix this problem? Or do you have other ideas on how I can ping the Scapy IP range to determine which hosts are on the network?

+7
source share
3 answers

You just need to make sure that reply not NoneType , as shown below ... sr1() returns None if you get a response timeout. You should also add timeout to sr1() , the default timeout is pretty absurd for your purposes.

 #!/usr/bin/python from scapy.all import * TIMEOUT = 2 conf.verb = 0 for ip in range(0, 256): packet = IP(dst="192.168.0." + str(ip), ttl=20)/ICMP() reply = sr1(packet, timeout=TIMEOUT) if not (reply is None): print reply.dst, "is online" else: print "Timeout waiting for %s" % packet[IP].dst 
+6
source

You cannot display the reply.src field if the return value of the variable is null. In other words, you need to check if a variable is returned with some value (if ping was successful). You can make an IF condition to get the .src field only when the variable is non-zero.

+2
source

FTR, Scapy supports implicit generators. It works:

 ans, unans = sr(IP(dst="192.169.0.1-255")/ICMP(), timeout=2) 

Then iterate over the answers.

This is probably much better :)

0
source

Source: https://habr.com/ru/post/897986/


All Articles