Python3 Implementing TCP port scanning

Source: Internet
Author: User

In the initial phase of penetration testing, we usually need to gather information about the target, and port scanning is a crucial step in information gathering. With port scanning we can see which services are open to the target host, and can even guess some vulnerabilities based on the service. TCP port scanning is generally divided into the following types:

    1. TCP Connect Scan: Also known as full-connection scan, this way directly connected to the target port, the completion of the TCP three handshake process, this way the scan results are more accurate, but the speed is relatively slow and can easily be detected by the target system.
    2. TCP SYN Scan: Also known as semi-open scan, this way sends a SYN packet, initiates a TCP session, and waits for the target response packet. If you receive an RST package, the port is closed, and if you receive a syn/ack packet, the corresponding port is open.
    3. TCP FIN Scan: This way sends a FIN packet that represents the removal of an active TCP connection and lets the other person close the connection. If an RST package is received, the corresponding port is closed.
    4. TCP Xmas Scan: This method is set to 1 packets by sending the PSH, FIN, URG, and TCP flag bits. If an RST package is received, the corresponding port is closed.

Below we will use Python3 to implement the TCP full-port scanner, the following into the programming link.

Coding combat

全连接扫描The core of the approach is to make a TCP connection for different ports and to determine if the port is open based on the success of the connection, now let's implement one of the simplest port scanners:

#!/usr/bin/python3#-*-coding:utf-8-*-from Socket import *def Portscanner (host,port):    try:        s = socket (af_inet , Sock_stream)        S.connect ((host,port))        print (' [+]%d open '% port)        s.close ()    except:        print (' [-]% D Close '% Port ' def main ():    setdefaulttimeout (1) for    p in range (1,1024):        portscanner (' 192.168.0.100 ', p) if __name__ = = ' __main__ ':    Main ()

The core of this code is the portScanner function, from which the content can be seen, just a simple TCP connection, if the connection is successful is determined to open the port, otherwise considered closed. Let's look at the results of the operation:

This kind of scan looks too inefficient, and actually very slow, because we set the default timeout of 1 seconds, this scan 10,000 ports, not to wait for the flowers to thank? The simplest way is to use it 多线程 to improve efficiency, although Python's multithreading is a bit too weak, but at least we can use the time we wait to do something else. In addition, before scanning the port more, the information displayed we look inconvenient, this time we only show what we care about 打开的端口 , and will open the number of ports at the end of the scan display.

#!/usr/bin/python3#-*-coding:utf-8-*-from socket import *import Threadinglock = Threading. Lock () opennum = 0threads = []def portscanner (host,port):    global Opennum    try:        s = socket (af_inet,sock_ STREAM)        S.connect ((host,port))        Lock.acquire ()        opennum+=1        print (' [+]%d open '% port)        Lock.release ()        s.close ()    except:        passdef Main ():    setdefaulttimeout (1) for    p in range (1,1024 ):        t = Threading. Thread (target=portscanner,args= (' 192.168.0.100 ', p))        Threads.append (t)        T.start () for         T in Threads:        t.join ()    print (' [*] the scan is complete! ')    Print (' [*] A total of%d open port '% (opennum)) if __name__ = = ' __main__ ':    Main ()

Run a look at the effect, such as:

Does this look much more convenient? At this point the efficiency of the problem solved, and now we also need to add a parameter resolution for the scanner function, so as to look like, can not always change the code to modify the scan target and port bar!

Parameter parsing we will use the standard module of Python3 argparse , so we can save ourselves the trouble of parsing the string! Here's a look at the code:

#!/usr/bin/python3#-*-coding:utf-8-*-from socket import *import threadingimport Argparselock = Threading.        Lock () opennum = 0threads = []def portscanner (Host,port): global Opennum try:s = socket (af_inet,sock_stream) S.connect ((Host,port)) Lock.acquire () opennum+=1 print (' [+]%d open '% port) Lock.relea SE () s.close () Except:passdef main (): P = argparse.    Argumentparser (description= ' Port scanner!. ') P.add_argument ('-h ', dest= ' hosts ', type=str) args = P.parse_args () hostList = Args.hosts.split (', ') setdefaulttim            Eout (1) for host in Hostlist:print (' Scanning the host:%s ... '% (host)) for P in range (1,1024): t = Threading.            Thread (target=portscanner,args= (host,p)) Threads.append (t) T.start () for T in Threads: T.join () print (' [*] The host:%s scan is complete! '% (host)) print (' [*] A total of%d open port ' % (Opennum)) if __name__ = = ' __main__ ': Main () 

Look at the effect of the operation, such as:

At this point our port scanner is basically completed, although the function is relatively simple, designed to express the basic implementation of port scanners ideas! As for the more detailed function can be based on this basic structure to gradually improve!

Summary

Python3 Implementing TCP port scanning

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.