Network Ping Sweep Utility for Windows by Corey Goldberg

Subscribe To Corey's Blog Subscribe To Goldblog goldb.org home



Python | Network Ping Sweep Utility for Windows

by Corey Goldberg - 2008

A Ping sweep is a technique used to determine which of a range of IP addresses map to live hosts. It consists of ICMP ECHO requests sent to multiple hosts. If a given address is live, it will return an ICMP_ECHO reply.


Usage:

> ping_sweep.py 192.16.1

Download:

ping_sweep.py


Ping Sweep Script:

#!/usr/bin/env python
#
#  ping_sweep.py
#  Host/Device Ping Utility for Windows
#  Corey Goldberg (www.goldb.org), 2008


import sys
import re
from subprocess import Popen, PIPE
from threading import Thread


num_threads = 128


def main():
    if len(sys.argv) != 1:
        ip_stem = sys.argv[1]
        if not re.match('^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$', ip_stem):
            print 'error: invalid ip_stem'
            print 'example: ping_sweep.py 192.168.1'
            sys.exit(1)
    else:
        print 'usage: ping_sweep.py ip_stem'
        print 'example: ping_sweep.py 192.168.1'
        sys.exit(1)
    ips = ['%s.%i' % (ip_stem, ip_end) for ip_end in range(256)]
    ip_buckets = split_seq(ips, num_threads)
    ip_buckets = []
    for seq in split_seq(ips, num_threads):
        ip_buckets.append(seq)
    PingSweep(ip_buckets)
    
    
def split_seq(seq, num_pieces):
    start = 0
    for i in range(num_pieces):
        stop = start + len(seq[i::num_pieces])
        yield seq[start:stop]
        start = stop

        
class PingSweep(object):
    def __init__(self, ip_buckets):
        print 'pinging hosts:\n'
        for thread_ref, ip_bucket in zip(range(num_threads), ip_buckets):
            sa = SweepAgent(ip_bucket)
            sa.start()
        
        
class SweepAgent(Thread):
    def __init__(self, ip_bucket):
        Thread.__init__(self)        
        self.ip_bucket = ip_bucket

    def run(self):
        for ip in self.ip_bucket:
            p = Popen('ping -n 1 ' + ip, stdout=PIPE)
            m = re.search('Average = (.*)ms', p.stdout.read())
            if m:
                print '%s is alive.  round trip time: %s ms' % (ip, m.group(1))
              
                             
if __name__ == '__main__':
    main()

Output:

pinging hosts:

192.168.12.20 is alive.  round trip time: 11 ms
192.168.12.18 is alive.  round trip time: 11 ms
192.168.12.22 is alive.  round trip time: 12 ms
192.168.12.38 is alive.  round trip time: 14 ms
192.168.12.24 is alive.  round trip time: 12 ms
192.168.12.30 is alive.  round trip time: 12 ms
192.168.12.17 is alive.  round trip time: 10 ms
192.168.12.28 is alive.  round trip time: 14 ms
Copyright © 2006-2008 Corey Goldberg  |