9

I'm attempting to write a Python script which uses the Scapy module to ping an internal IP range to determine which IP's are online. I've got this so far:

#!/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 it with a single IP address, instead of 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"

Anyone know how I can fix this problem? Or do you have any other ideas on how I can ping an IP range with Scapy, to determine which hosts are online?

user961124
  • 111
  • 1
  • 1
  • 3
  • Your issue has to do with assigning the return value of `sr1(packet)` to reply. I'm not familiar with `scapy` so I can't provide anymore help than that, but start there. – brc Sep 24 '11 at 19:00

3 Answers3

7

You just need to ensure that reply is not NoneType as illustrated below... sr1() returns None if you get a timeout waiting for the response. You should also add a timeout to sr1(), the default timeout is quite 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
Mike Pennington
  • 41,899
  • 19
  • 136
  • 174
  • wouldn't packet[IP].src print the source IP i.e. if you are pinging from 10.1.1.1 to 10.1.1.7 and it fails - the reply would be "Timeout waiting for 10.1.1.1" instead of "Timeout waiting for 10.1.1.7"? – Saurabh Hirani Nov 12 '13 at 09:32
2

You can't show reply.src field if the return of variable is null. In other words, you need to validate if the variable has return with some value (if the ping was successful). You can make an IF condition to get the .src field only when variable is not null.

StarkBR
  • 227
  • 8
  • 15
1

FTR, Scapy supports implicit generators. This works:

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

Then iterate through the answers.

It is probably much better :)

Cukic0d
  • 5,111
  • 2
  • 19
  • 48