


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!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.