Sharing of multi-thread port scanning tools implemented by Python and python port scanning

Source: Internet
Author: User

Sharing of multi-thread port scanning tools implemented by Python and python port scanning

It was written two nights last night and finally the Py Port Scanner was finished. Let's call it version 0.1 as a Python multi-thread Port scanning tool.

The level is limited. To tell the truth, there are some puzzles and puzzles in the middle, and the Code may also be messy. I hope you will understand that we have not found a good solution to some problems. I think it's okay to test the speed.

Send two copies of the IP address and IP address segment:

Source code:

Copy codeThe Code is as follows:
#-*-Coding: UTF-8 -*-
_ Author _ = 'phtih0n'
Import threading, socket, sys, cmd, OS, Queue

# Scan common ports
PortList = [21, 22, 23, 25, 80,135,137,139,445,143 3, 1502,330 6, 3389,808 0, 9015]
# Get a queue
Def GetQueue (list ):
PortQueue = Queue. Queue (65535)
For p in list:
PortQueue. put (p)
Return PortQueue

# Number of Single IP scan threads
NThread = 20
# Thread lock
Lock = threading. Lock ()
# Timeout
Timeout = 3.0
# Open Port list
OpenPort = []

Class ScanThread (threading. Thread ):
Def _ init _ (self, scanIP ):
Threading. Thread. _ init _ (self)
Self. IP = scanIP

Def Ping (self, Port ):
Global OpenPort, lock, Timeout
Sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
Sock. settimeout (Timeout)
Address = (self. IP, Port)
Try:
Sock. connect (address)
Except t:
Sock. close ()
Return False
Sock. close ()
OpenPort. append (Port)
If lock. acquire ():
Print "IP: % s Port: % d" % (self. IP, Port)
Lock. release ()
Return True


Class ScanThreadSingle (ScanThread ):
Def _ init _ (self, scanIP, SingleQueue ):
ScanThread. _ init _ (self, scanIP)
Self. SingleQueue = SingleQueue

Def run (self ):
While not self. SingleQueue. empty ():
P = self. SingleQueue. get ()
Self. Ping (p)


Class ScanThreadMulti (ScanThread ):
Def _ init _ (self, scanIP, PortList ):
ScanThread. _ init _ (self, scanIP)
Self. List = PortList [:]

Def run (self ):
For p in self. List:
Self. Ping (p)

Class Shell (cmd. Cmd ):
U'''py Port usage 0.1 instructions:
Port [port ..] specifies the scan port, which is separated by commas.
Default Value: 21, 22, 23, 25, 80,135,137,139,445,143 3, 1502,330 6, 3389,808 0, 9015
Example: port 21,23, 25
Example: port 1000 .. 2000
Example: port 80,443,100 0 .. 1500
Scan [IP] scan an IP address
Example: scan 192.168.1.5
Search [IP begin]-[IP end] scans an IP segment
Example: search 192.168.1.1-192.168.1.100
Time [timeout] sets the timeout time. The default value is 3 seconds.
Example: time 5
Cls clear screen content
Listport print port list
Help open this help
'''
Def _ init _ (self ):
Cmd. Cmd. _ init _ (self)
Reload (sys)
Sys. setdefaultencoding ('utf-8 ')
Self. prompt = "Port Scan>"
Self. intro = "Py Port limit 0.1"

Def do_EOF (self, line ):
Return True

Def do_help (self, line ):
Print self. _ doc __

# Set the port
Def do_port (self, line ):
Global PortList
PortList = []
ListTmp = line. split (',')
For port in ListTmp:
If port. find ("..") <0:
If not port. isdigit ():
Print "input error"
Return False
PortList. append (int (port ))
Else:
RangeLst = port. split ("..")
If not (RangeLst [0]. isdigit () and RangeLst [1]. isdigit ()):
Raise ValueError
Exit ()
For I in range (int (RangeLst [0]), int (RangeLst [1]):
PortList. append (I)

Def do_scan (self, line ):
Global nThread, PortList
ThreadList = []
StrIP = line
SingleQueue = GetQueue (PortList)
For I in range (0, nThread ):
T = ScanThreadSingle (strIP, SingleQueue)
ThreadList. append (t)
For t in ThreadList:
T. start ()
For t in ThreadList:
T. join ()

Def do_search (self, line ):
Global nThread, PortList
ThreadList = []
(BeginIP, EndIP) = line. split ("-")
Try:
Socket. inet_aton (BeginIP)
Socket. inet_aton (EndIP)
Except t:
Print "input error"
Return
IPRange = BeginIP [0: BeginIP. rfind ('.')]
Begin = BeginIP [BeginIP. rfind ('.') + 1:]
End = EndIP [EndIP. rfind ('.') + 1:]
For I in range (int (begin), int (end )):
StrIP = "% s. % s" % (IPRange, I)
T = ScanThreadMulti (strIP, PortList)
ThreadList. append (t)
For t in ThreadList:
T. start ()
For t in ThreadList:
T. join ()

Def do_listport (self, line ):
Global PortList
For p in PortList:
Print p,
Print '\ N'

Def do_time (self, line ):
Global Timeout
Try:
Timeout = float (line)
Except t:
Print u "parameter error"

Def do_cls (self, line ):
OS. system ("cls ")


If '_ main _' = _ name __:
Try:
OS. system ("cls ")
Shell = Shell ()
Shell. nested loop ()
Except t:
Exit ()

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.