Hello I am kind of a new programmer in python and I tryed to do a port scanner.
I have a problem here but I can gigure it out' when I try to compile it it just gets stuck :S

Here is the code

import socket as sk
import sys
import threading

# open file
file = open('results.txt', 'a')

MAX_THREADS = 0

def usage():
    print "\npyScan 0.1"
    print "usage: pyScan <port> [start ip] [end ip] [thread]"

class Scanner(threading.Thread):
    def __init__(self, host, port):
        threading.Thread.__init__(self)
        # host and port
        self.host = host
        self.port = port
        # build up the socket obj
        self.sd = sk.socket(sk.AF_INET, sk.SOCK_STREAM)

    def run(self):
        try:
            # connect to the given host:port
            self.sd.connect((self.host, self.port))
            print "%s:%d OPEN" % (self.host, self.port)
            strScan = str(self.host) + ':' + str(self.port) + '\n'
            file.write(strScan)

            self.sd.close()
        except: pass

class pyScan:
    def __init__(self, args=[]):
        # arguments vector
        self.args = args
        # start ip and end ip
        #self.startip
        #self.stopip
        #port number
        self.port = ""
        # threads
        self.threads = self.args[4]
        MAX_THREADS = int(self.threads)

         #check validity of ips
        ip1 = self.args[2]
        ip2 = self.args[3]
        l1 = ip1.split('.')
        l2 = ip2.split('.')

        sum1= int(l1[0]) + int(l1[1]) + int(l1[2]) +int(l1[3])
        sum2= int(l2[0]) + int(l2[1]) + int(l2[2]) +int(l2[3])
        #_____________________________________________


        # check the arguments
        if len(self.args) == 5:
            self.port = self.args[1]
            try:
                self.startip = self.args[2]
                self.stopip = self.args[3]
                strStar = '========= Scan: ' + str(self.startip) + ' - ' + str(self.stopip) + ' ,   Port: ' + str(self.port) + ' Threads: ' + str(MAX_THREADS) + ' =========\n'
                file.write(strStar)
            except ValueError:
                usage()
                return
        #Check Validity of ip
            if sum1 > sum2:
                usage()
                return
        elif len(self.args) == 2:
            self.host = self.args[1]

        else:
            usage()
            return

        try:
            sk.gethostbyname(self.host)
        except:
            print "hostname '%s' unknown" % self.host
        self.scan(self.startip, self.stopip, self.port, MAX_THREADS)

    def scan(self, startip, stopip, port, threads):



        self.port = port
        list1 = startip.split('.')
        list2 = stopip.split('.')
        #Times  is ip count from startip to stopip
        times = (255 - int(list1[3])) + ((int(list2[2]) - int(list1[2]) - 1) * 255) + int(list2[3]) + (int(list2[2])-int(list1[2])) + ((int(list2[1]) - int(list1[1])) * 255 *255) + ((int(list2[0]) - int(list1[0])) * 255 * 255 * 255)
        nlist1 = [int(list1[0]), int(list1[1]), int(list1[2]), int(list1[3])]
        nlist2 = [int(list2[0]), int(list2[1]), int(list2[2]), int(list2[3])]
        i = 0
        while threading.activeCount() < threads:
                    for i in range(times):
                         host = list1[0] + "." + list1[1] + "." + list1[2] + "." + list1[3]
                         Scanner(str(host), self.port).start()
                         nlist1[3] = ((++nlist1[3]) %256 )
                         if nlist1[3] != 0:
                              nlist1[2] = ((++nlist1[2]) %256 )
                              if nlist1[2] != 0:
                                    nlist1[1] = ((++nlist1[1]) %256 )
                                    if nlist1[1] != 0:
                                        nlist1[0] = ((++nlist1[0]) %256 )

        file.write('====================== Scan Is Over ==========================\n\n\n')
        file.close()
if __name__ == "__main__":
    pyScan(sys.argv)

Recommended Answers

All 4 Replies

#!/usr/bin/env python
 
from socket import *
import sys, time
from threading import Thread
 
class Pscan(Thread):
    """
    A simple port scanner, just returns whether
    a port is open, and displays the results in a semi-graphical way.
 
    Usage:
    %s <host> [start port] [stop port]
 
    Changelog:
    v0.1 - Basic scan
    v0.2 - Added banner grabbing for very simple process identification
    """ % sys.argv[0]
    def __init__(self, host, minport=1, maxport=1024):
        Thread.__init__(self)
        try:
            self.host = host
            self.minport = minport
            self.maxport = maxport
        except:
            print self.__doc__
            sys.exit(1)
 
    def run(self):
        print "Scanning... (Please be patient)"
        starttime = time.time()
        popen = 0
        for x in range(self.minport,self.maxport):
            s = socket(AF_INET, SOCK_STREAM)
            try:
                s.connect((self.host, x))
                print "Port %d is open!" % x
                popen += 1
                s.close()
            except error:
                pass
        if not popen:
            print """
        No ports in the range %d-%d found to be open on host %s
        Host may be down or just have all the ports closed.
            """ % (self.minport, self.maxport, self.host)
        else:
            total = time.time() - starttime
            print "Scan complete in %d seconds" % total
 
if len(sys.argv) == 4:
    ip = sys.argv[1]
    min = int(sys.argv[2])
    max = int(sys.argv[3])
    Pscan(ip,min,max).start()
elif len(sys.argv) == 2:
    ip = sys.argv[1]
    Pscan(ip).start()
else:
    ip = raw_input("What ip do you want to scan? ")
    min = input("From port? ")
    max = input("To port? ")
    Pscan(ip,min,max).start()

This is the one I use.

this scanner does not do what my scanner does
this scanner scans an ip for the ports you enter to it
my scannet takes an area of ip's and scans one port that is open in all of them
i.e
in this area of ip's 0.0.0.0-255.255.255.255 it searches where the port 10000 is open

post a traceback of the error.

Just on first look your main while loop in the scan function isn't right.

Try changing it to:

for i in range(times):
    host = list1[0] + "." + list1[1] + "." + list1[2] + "." + list1[3]

    while threading.activeCount() >= threads:
        time.sleep(.1)

    Scanner(str(host), self.port).start()
    nlist1[3] = ((++nlist1[3]) %256 )
    if nlist1[3] != 0:
        nlist1[2] = ((++nlist1[2]) %256 )
        if nlist1[2] != 0:
            nlist1[1] = ((++nlist1[1]) %256 )
            if nlist1[1] != 0:
                nlist1[0] = ((++nlist1[0]) %256 )
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.