Home > Article > Backend Development > Detailed explanation of graphic code for making TCP port scanner using Python3
This article shares with you the production process of using Python3 to implement a TCP full-connection port scanner, including ideas and code. It is very simple and easy to understand. I recommend it to everyone
In penetration In the preliminary stage of testing, we usually need to collect information about the attack target, and port scanning is a crucial step in information collection. Through port scanning, we can learn what services are open on the target host, and we can even guess that there may be certain vulnerabilities based on the services. TCP port scans are generally divided into the following types:
TCP connect scan: also called full connection scan, this method directly connects to the target port and completes the TCP three-way handshake process. This method scan results More accurate, but slower and easily detected by the target system.
TCP SYN scan: Also known as semi-open scan, this method will send a SYN packet, start a TCP session, and wait for the target response packet. If a RST packet is received, it indicates that the port is closed, and if a SYN/ACK packet is received, it indicates that the corresponding port is open.
Tcp FIN scan: This method sends a FIN packet indicating the teardown of an active TCP connection, allowing the other party to close the connection. If a RST packet is received, it indicates that the corresponding port is closed.
TCP XMAS scanning: This method sends packets with PSH, FIN, URG, and TCP flag bits set to 1. If a RST packet is received, it indicates that the corresponding port is closed.
Next we will use Python3 to implement the TCP full connection port scanner, and then enter the programming link.
Coding practice
Full connection scan
The core of the method is to conduct TCP connections for different ports, and determine whether the port is open based on whether the connection is successful. Now let's implement the simplest port scanner:
#!/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. It can be seen from the content that it only performs A simple TCP connection is made. If the connection is successful, it is judged that the port is open, otherwise it is considered closed. Let’s take a look at the running results:
Such a scan seems too inefficient, and it is actually very slow because we set the default timeout to 1 second. If we scan 10,000 ports, wouldn't we have to wait until the flowers have withered? The simplest way is to use multithreading
to improve efficiency. Although python's multithreading is a bit too weak, we can at least use the time we wait to do something else. In addition, there were many ports scanned before, and the displayed information seemed inconvenient for us. This time we only display the open ports
we care about, and display the number of open ports at the end of the scan.
#!/usr/bin/python3 # -*- coding: utf-8 -*- from socket import * import threading lock = threading.Lock() openNum = 0 threads = [] 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: pass def 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 it and see the effect, as shown below:
Does it look more convenient now? At this point, the efficiency problem has been solved. Now we still need to add a parameter parsing function to the scanner so that it can look decent. We can't change the code every time to modify the scanning target and port!
Parameter analysis We will use the standard module argparse
that comes with python3, so that we save the trouble of parsing the string ourselves! Let’s look at the code:
#!/usr/bin/python3 # -*- coding: utf-8 -*- from socket import * import threading import argparse lock = threading.Lock() openNum = 0 threads = [] 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: pass def main(): p = argparse.ArgumentParser(description='Port scanner!.') p.add_argument('-H', dest='hosts', type=str) args = p.parse_args() hostList = args.hosts.split(',') setdefaulttimeout(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()
Take a look at the running effect, as shown below:
At this point, our port scanner is basically completed, although the function is relatively simple. , aiming to express the basic implementation ideas of the port scanner! As for more detailed functions, they can be gradually improved based on this basic structure!
Summary
This section mainly explains the process of implementing a simple port scanner in Python3. This experiment uses Tcp full connection and continuously tries to connect to the host. Although there are some shortcomings, this method is most suitable for beginners to learn. As for more complex methods, it will not be difficult to learn in the future. Friends who want to draw inferences from one example can complete the scan and output the protocol at the same time based on the comparison relationship between the protocol and the port. This will look better. As for the more detailed functions, I will leave it to you to do Exercise!
The above is the detailed content of Detailed explanation of graphic code for making TCP port scanner using Python3. For more information, please follow other related articles on the PHP Chinese website!