Thread: scan program

Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. Only the strong survives!!.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Feb 2003
    Location
    A World of wonders.
    Posts
    5,583
    Rep Power
    407

    scan program


    Im tring to create a port scanner ( knowledge only ) but for some reason it just halts. I mean it does not want to scan anything.. any idea?

    Code:
    BUFF_SIZE      = 1024
    
    def Scan_Host( ):
    
            for ports in range( 1, BUFF_SIZE ):
    
                    host   =  "localhost"
                    sock   = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    
                    if sock.connect_ex(( host, int( ports ))):
    
                            print ports, '/tcp'
    
    
    if __name__ == '__main__':
    
                    Scan_Host( )
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    133
    Rep Power
    12
    Try replacing "print ports, '/tcp' with:
    Code:
    sys.stdout.write("%i/tcp" % port)
    sys.stdout.flush()
  4. #3
  5. Only the strong survives!!.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Feb 2003
    Location
    A World of wonders.
    Posts
    5,583
    Rep Power
    407
    Ok sorry i just realized that it scans.. but it takes a really really long time.. is there a way to speed it up abit?
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    624
    Rep Power
    34
    A long time indeed. The default socket timeout is 30 seconds, which means 8 hours for a full scan of your 1024 ports.

    Check socket.settimeout(s) to lower the time.
    Also consider threading.

    Incidentally, BUFF_SIZE? Not max_port_no?
  8. #5
  9. Only the strong survives!!.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Feb 2003
    Location
    A World of wonders.
    Posts
    5,583
    Rep Power
    407
    Yes its what i did.. i whent along with using threading.. but... when i try it out on linux.. everything works well.. but on windows.. thats another case.. i keep getting an error about Undefine name Thread cant seem to think why cause everything seems to be in place

    This is when running it on cmd ( python gui consule works )

    Code:
    Traceback (most recent call last):
      File "progs/pscanner.py", line 6, in ?
        class PortScan( Thread ):
    NameError: name 'Thread' is not defined
    when i try to wrapp it with py2exe i get the same error

    Code:
    class Scan( Thread ):
    
            def __init__ ( self, uhost, port ):
                    Thread.__init__( self )
    
                    self.host  = uhost
                    self.port  = port
    
            def run( self ):
                    
                    try:
                        sock  = socket( AF_INET, SOCK_STREAM )
                        sock.connect(( self.host, self.port ))
    
                        print '%d/tcp \t Open' % self.port
                        
                        sock.close( )
    
                    except error:
                        pass
    
                  
                    
    
    
    if __name__ == '__main__':
    
                    try:
                        
                        hosts  = argv[1]
                        ports  = int( 664 )
    
                        e = Event( )
                        
                        for Ports in range( 1, ports ):
                            
                                try:
                                        if( activeCount( ) >= ports ):
                                            
                                                e.clear( )
                                                e.wait( )
    
                                        start_scan   = Scan( hosts, Ports )
                                        start_scan.start( )
                                        
                                except error:
                                        pass
    
                    except IndexError:
                        
                            print 'Usage: %s <host/ip address>' % argv[0]
    Last edited by xlordt; June 10th, 2004 at 12:14 PM.
  10. #6
  11. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    Code:
    from threading import Thread
    ??
  12. #7
  13. Only the strong survives!!.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Feb 2003
    Location
    A World of wonders.
    Posts
    5,583
    Rep Power
    407
    Originally Posted by Grim Archon
    Code:
    from threading import Thread
    ??
    I was just tring it out.. cause got kinda mad cause.. it wasnt working , i still get that damn erro.. since last night i have been tring ti figure out what is up.. did what you said.. and now i get..
    Code:
    Traceback (most recent call last):
      File "progs/pscanner.py", line 2, in ?
        from threading import Thread
    ImportError: cannot import name Thread
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    624
    Rep Power
    34
    Are you running the latest version of Python?
  16. #9
  17. Only the strong survives!!.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Feb 2003
    Location
    A World of wonders.
    Posts
    5,583
    Rep Power
    407
    hmm weird i just opend the python idle it said.. im running 2.3.2.. will download the latest then see whats up, but im sure i downloaded the latest version
  18. #10
  19. Only the strong survives!!.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Feb 2003
    Location
    A World of wonders.
    Posts
    5,583
    Rep Power
    407
    Ok just upgraded to 2.3.4 and im still getting the same problem arg!!

    Code:
    from socket import *
    from threading import *
    from sys import argv
    error:
    Code:
    G:\Python23>python.exe progs/pscanner.py
    Traceback (most recent call last):
      File "progs/pscanner.py", line 6, in ?
        class Scan( Thread ):
    NameError: name 'Thread' is not defined
    the module is there cause i checked
    Last edited by xlordt; June 10th, 2004 at 01:09 PM.
  20. #11
  21. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    I put the import statements in the same file as the Scan class.

    I had to check that
    from socket import * did not get stuff replaced by
    from threading import * (nasty code )

    On my Windows machine it did not cause any problem and ran as expected.

    On my Redhat machine it caused threading to complain after port 68 saying thread.error: can't start new thread but did scan up to that number I think.

    It may be some Linux security limit I am not aware of but what it looks like to me is an implementation difference.

    Not sure (it's late) if the code should run at all but I just ran it under Python 2.2 on my redhat machine and it got upto port 663 but did not report back any results.

    grim
    Last edited by Grim Archon; June 10th, 2004 at 07:09 PM.
  22. #12
  23. Only the strong survives!!.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Feb 2003
    Location
    A World of wonders.
    Posts
    5,583
    Rep Power
    407
    Everything works smothly on my slackware partion.. but on windows.. everything seems to fail... heh cant seem to see why, even if i tried
    Code:
    from threading import Thread
    I still get the same error, like i said.. this error only happends on cmd but not on python idle program weird.
  24. #13
  25. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    You don't happen to have a module called threading in your progs sub-directory do you? Maybe it has something to do with your search path.

    Just in case something funny is going on - try this version..

    You could add a print statement to confirm it is all there.
    Code:
    import socket
    import threading
    import sys
    
    print dir(threading)
    
    class Scan(threading.Thread): 
    
            def __init__(self, uhost, port): 
                    threading.Thread.__init__(self)
                    self.host = uhost
                    self.port = port
    
            def run(self): 
                    try: 
                        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                        sock.connect((self.host, self.port))
                        print '%d/tcp \t Open'%self.port
                        sock.close()
                    except socket.error: 
                        #print self.port,
                        pass
    
    if __name__ == '__main__': 
                    try: 
                        hosts = sys.argv[1]
                        ports = int(664)
                        for Ports in range(1, ports): 
                            start_scan = Scan(hosts, Ports)
                            start_scan.start()
    
                    except IndexError: 
                        
                            print 'Usage: %s <host/ip address>'%argv[0]
  26. #14
  27. Only the strong survives!!.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Feb 2003
    Location
    A World of wonders.
    Posts
    5,583
    Rep Power
    407
    ya i got it fixed ( by reinstalling xp hehe ) but anyways.. one more thing.. im tring to get this to pring out.. done once its done scanning.. i pretty mutch got it working well.. just need it to say.. done.. but im not knowledgable enough to figure it out yet... still reading py docs

    Code:
    from threading import Thread, Event, activeCount
    from socket import *
    import time, sys
    
    
    class ScanHost( Thread ):
    
            def __init__ ( self, host, port, evt ):
                    Thread.__init__ ( self )
    
                    self.host   =  host
                    self.port   =  port
                    self.evt    =  evt
    
            def run( self ):
    
                try:
                        s   = socket( AF_INET, SOCK_STREAM )
                        con = s.connect(( self.host, self.port ))
    
                        print self.port, '\t tcp\t Open'
                                
                        s.close( )
           
                except error:
                        pass
                    
                self.evt.set( )
             
    
    
    
    if __name__ == '__main__':
    
            try:
                    ThreadList = []
                    
                    host      = 'localhost'
                    max_ports = int( 644 ) + 1
    
                    thr_event = Event( )
                    
                    for ports in range( 1, max_ports ):
                        
                            try:
                                    if( activeCount( ) >= max_ports ):
    
                                            thr_event.clear( )
                                            thr_event.wait( )
    
                                    setinformation  =  ScanHost( host, ports, thr_event )
                                    ThreadList.append( setinformation )
                                    
    
                            except error:
                                    pass         
    
             
                    for ports in ThreadList:
    
                                        ports.start( )
                                        time.sleep( 0.1 )
    
                                                            
    
            except IndexError:
    
                    print 'An error was caused'
  28. #15
  29. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    Here's a version that basically waits for all the threads to finish. I have also split the number of threads created at any one timne - to spare the system and also because large ranges made some of my Python installs unstable.
    Code:
    import socket
    import threading
    import sys
    import Queue
    
    class Scan(threading.Thread): 
            counter = 0
            def __init__(self, uhost, port, que, ready, finished, lock): 
                    threading.Thread.__init__(self)
                    self.host = uhost
                    self.port = port
                    self.ready = ready
                    self.finished = finished
                    self.que = que
                    self.lock = lock
    
            def run(self): 
                    self.lock.acquire()
                    Scan.counter = Scan.counter+1
                    self.lock.release()
                    self.ready.wait(1.0)
                    try: 
                        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                        sock.connect((self.host, self.port))
                        self.que.put(self.port)
                        sock.close()
                    except socket.error: 
                        pass
                    self.lock.acquire()
                    Scan.counter = Scan.counter-1
                    if Scan.counter <= 1: 
                        self.finished.set()
                    self.lock.release()
    
    if __name__ == '__main__': 
                    try: 
                        scan_size = 20
                        que = Queue.Queue()
                        hosts = sys.argv[1]
                        port_start = int(sys.argv[2])
                        port_end = int(sys.argv[3])
                        trigger = threading.Event()
                        trigger.clear()
                        holdoff = threading.Event()
                        holdoff.clear()
                        lock = threading.Lock()
                        for sub_ports in range(port_start, port_end+1, scan_size): 
                            for port in range(sub_ports, sub_ports+scan_size): 
                                start_scan = Scan(hosts, port, que, trigger, holdoff, lock)
                                try: 
                                    start_scan.start()
                                except: 
                                    print "Scansize of ", scan_size, "is too big for this system."
                                    sys.exit(1)
                            #Now really start all the scanning threads
                            trigger.set()
                            #Wait for all the threads to finish
                            holdoff.wait(20.0)
                            out = []
                            while True: 
                                try: 
                                    out.append(que.get(False))
                                except Queue.Empty: 
                                    out.sort()
                                    for n in out: 
                                        print "%6d/tcp\tOpen"%n
                                    break
                        print "Finished"
    
                    except IndexError: 
                            print 'Usage: %s <host/ip address> port_start port_end'%sys.argv[0]
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo