Python multithreaded Scan Port example

Source: Internet
Author: User
The code is as follows:


#-*-coding:cp936-*-
Import socket
From threading Import Thread,activecount,lock
From time import CTime
Mutex = Lock ()

Class Loop (Thread):
def __init__ (Self,ip,port,que):
Thread.__init__ (self)
Self.ip = IP
Self.port = Port
Self.que = que

def run (self):
Global Mutex
Try
Client = Socket.socket ()
Indicator = CLIENT.CONNECT_EX ((self.ip,self.port))
If Mutex.acquire (1):
If indicator = = 0:
Que.append (self.ip+ ' \ t ' +str (Self.port))
Else
Print Self.ip, ' \ t ', str (self.port), ' unreachable '
Mutex.release ()
Except
If Mutex.acquire (1):
Print Self.ip, ' \ t ', str (self.port), ' unreachable '
Mutex.release ()

Class Main (Thread):
def __init__ (Self,ip,que):
Thread.__init__ (self)
Self.ip = IP
Self.que = que

def run (self):
i = 0
While I < 65536:
If Activecount () <= 200:
Loop (Ip=self.ip,port=i,que=self.que). Start ()
i = i + 1

if __name__ = = ' __main__ ':
que = []
ip = raw_input (' ip= ')

Main = Main (IP = ip,que = que)
Main.start ()

While True:
If Activecount () <= 1 and main.isalive () = = False:
Break

print '
f = open (' portopen.py ', ' a ')
F.write ("'")
F.write (CTime () + ' \ n ')
F.flush ()
For I in range (0,len (que)):
Print Que[i]
F.write (' \ t ' +que[i]+ ' \ n ')
F.flush ()
F.write ("'")
F.close ()

Raw_input ()

"Mon Jan 13 07:12:53 2014
localhost 135
localhost 1028
localhost 8048
localhost 8080
localhost 8181
localhost 8730
localhost 12040
localhost 12897
localhost 18040
localhost 18611
"" Tue Jan 14 10:04:58 2014
localhost 135
localhost 1028
localhost 8048
localhost 8080
localhost 8181
localhost 12897
localhost 18040
localhost 18611
'''

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.