Sunday, October 3, 2010

Python Program to Scan IP's and Ports

Here is a program I wrote in Python to scan a range of IP's and a chosen port :

I started with this code first from class :

**************

Here's the code we started with:
import socket
IPRange = raw_input('Enter an IP Address: ')
Port = input('Enter the Port Number: ')
a, b, c, d = IPRange.split('.')
for x in range(1, 254):
    ip = a + '.' + b + '.' + c + '.' + str(x)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((ip, Port))
    except socket.error:
        print '%s: Port Closed' % ip
        continue
    print '%s: Port Open' % ip


****************


import socket
IPRange = raw_input('Enter an IP Address: ')
UserInput = raw_input('Enter IP Class to scan (A/B/C): ')
Port = input('Enter the Port Number: ')
a, b, c, d = IPRange.split('.')

if UserInput == 'C':
    for x in range(1, 254):
        ip = str(a) + '.' + str(b) + '.' + str(c) + '.' + str(x)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.connect((ip, Port))
        except socket.error:
            print '%s: Port Closed' % ip
            continue
        print '%s: Port Open' % ip
elif UserInput == 'B':
    for y in range(1, 254):
        for x in range(1,254):
            ip = str(a) + '.' + str(b) + '.' + str(y) + '.' + str(x)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                s.connect((ip, Port))
            except socket.error:
                print '%s: Port Closed' % ip
                continue
            print '%s: Port Open' % ip
elif UserInput == 'A':
    for z in range(1, 254):
        for y in range(1,254):
            for x in range(1,254):
                ip = str(a) + '.' + str(z) + '.' + str(y) + '.' + str(x)
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                try:
                    s.connect((ip, Port))
                except socket.error:
                    print '%s: Port Closed' % ip
                    continue
                print '%s: Port Open' % ip
else:
    print '%s: Input Error try again'


The above screenshot shows how the program works.  It prompts you first for an ip address, then class and finally a port number (this would fail as the ip that I entered is not a web server).

Although I can see how this is useful to be able to write some apps using python, I much prefer using some prebuilt apps like Nmap which is far more flexible and powerful to be able to scan a range or ip's and ports.

No comments:

Post a Comment