[network security] 34. Implementation of Python attack and defense, IP and port scanner, multithreaded C-segment scanner

Article directory:

  • 1, Python multithreading
  • 2, Programming ping scanning
  • 3, Detect IP address
  • 4, Programming port scanner
  • 5, Multithreading + Queue to realize C-segment scanning
  • 6, Summary

Author's github resources:

  • Reverse analysis: https://github.com/eastmountyxz/ SystemSecurity-ReverseAnalysis
  • Network security: https://github.com/eastmountyxz/ NetworkSecuritySelf-study

Statement: I firmly oppose the use of teaching methods for criminal acts. All criminal acts will be severely punished. The green network needs our joint maintenance. It is recommended that you understand the principles behind them and better protect them. The sample will not be shared with you, and the analysis tool will be shared.

1, Python multithreading

1. Processes and threads

Process: it is an execution of a program. Each process has its own address space, memory, data stack and other auxiliary data recording the running track.

Threads: all threads run in the same process and share the same running environment. Thread has three parts: start, sequential execution and end.

Due to the low efficiency of single thread, multi-threaded programming is often introduced into programs. The core of the computer is the CPU, which undertakes all the computing tasks. It is like a factory running all the time. Assuming that the power of the factory is limited, only one workshop can be supplied at a time. In other words, when one workshop starts, other workshops must stop working. The implication is that a single CPU can only run one task at a time.

A process is like a workshop in a factory. It represents a single task that the CPU can handle. At any time, the CPU always runs one process and other processes are not running. There can be many workers in a workshop. They worked together to complete a task. Threads are like workers in a workshop. A process can include multiple threads.

2.thread module

Python thread module can call the following functions to enable multithreading. It will generate a new thread in which the function is called with the specified parameters and optional kwargs.

  • startnewthread(function, args kwargs=None)

Note: when using this method, you must add the time.sleep() function, otherwise each thread may not execute. This method also has a disadvantage. When encountering complex problems, the number of threads is not easy to control.

The output results are shown in the figure below:

3.threading module

thread module has some disadvantages, especially the number of threads can not be controlled. Next, we use threading to solve the problem that the number of threads can be controlled.

  • Using threading module
  • Subclass Thread class

The output result is shown in the figure below. Three threads occur at the same time.

The multi threading method can control the number of threads. For example, you want to write the requests module to get the status of the website_ Code status code.

The output results are shown in the figure below:

2, Programming ping scanning

The above code briefly explains the multi-threaded use of thread and threading modules. But what is the use in practical application? We can scan the addresses of all C segments through it and ping to detect whether they are alive. The code is as follows.

If the input ip address is local, the normal connection result is output, as shown below.

If the ip address entered is of the local computer, a timeout will be prompted, as shown in the following figure.

Then think: how to ping a segment C URL?

The basic idea is to design a loop. If the host does not exist, the timeout is returned; If the host exists, it contains the word TTL. Here, TTL is used as the judgment standard to judge the surviving data.

The output result is "UP".

3, Detect IP address

Next, we try to detect the ip address survival of the ichunqiu website. First, call the ping command to detect the ip address of the website, i.e. 117.23.xx.xx. (for this part, please refer to I Chunqiu ADO teacher. Thank you again.)

Ping here_ The check() function sets a transfer parameter corresponding to the ip address and detects it; ip address survivability detection is realized through thread thread, which can detect many surviving hosts.

The output result is shown in the figure below, in which the IP value is also recognized.

Question: in multithreaded programming, several threads are started at the same time, so the output is also output on one line. How can I wrap the output? System output is used here.

Output results by line, as shown in the following figure:

4, Programming port scanner

When we get a website, we need to scan its open ports. For example, through the online tool TScan, the scanning results are shown in the figure below, opening ports 80, 443, 8080, 7777, etc. Can we write code in Python? Functions similar to NMAP.

  • https://scan.top15.cn/

1.socket method

Python can scan the port through socket communication. By establishing a TCP socket, send TCP SYN packets to the port and wait for the corresponding TCP ACK to determine whether the port is open.

Full code:

# -*- coding: utf-8 -*-
import optparse
import socket
from socket import *

#Socket connection
def connScan(tgtHost, tgtPort):
        conn = socket(AF_INET, SOCK_STREAM)
        conn.connect((tgtHost, tgtPort))
        #conn.send('Violent Python\n')
        #results = conn.recv(100)
        print(' [+] %d/tcp open ' % tgtPort)
    except Exception as err:
        print(' [-] %d/tcp closed' % tgtPort)
#Scan port
def portScan(tgtHost, tgtPorts):
        tgtIP = gethostbyname(tgtHost)
        print("[-] Cannot resolve '%s': Unknown host" % tgtHost)
        tgtName = gethostbyaddr(tgtIP)
        print("[+] Scan Results for: " + tgtName[0])
        print("[+] Scan Results for: " + tgtIP)
    for tgtPort in tgtPorts:
        print(" Scanning port " + tgtPort)
        #Connection port
        connScan(tgtHost, int(tgtPort))

#The main function optparse handles command line arguments
def main():
    parser = optparse.OptionParser("usage%prog "+ \
                "-H <target host> -p <target port>")
    parser.add_option('-H', dest='tgtHost', type='string', \
                help='specify target host')
    parser.add_option('-p', dest='tgtPort', type='string', \
                help='specify target port[s] separated by comma')

    #Parse the parameter values entered by the script
    (options, args) = parser.parse_args()
    tgtHost = options.tgtHost
    tgtPorts = str(options.tgtPort).split(',')
    if (tgtHost==None) or (tgtPorts[0]==None):
        print('[-] You must specify a target host and port[s].')

    #Port scan
    portScan(tgtHost, tgtPorts)
if __name__ == '__main__':

The code uses the optparse parameter definition, including the host to be scanned and the port to be scanned. The running results are shown in the figure below. The open ports 80, 443, 777 and 9080 are successfully identified.

Similarly, we can simply write the above code to scan the custom IP port sequence.

The output results are as follows:

2.telnetlib method

Next, we refer to Dahlhin's article to supplement the Python built-in module telnetlib, which can also complete the task of port detection.

  • https://www.cnblogs.com/dachenzi/p/8676104.html

The output result is that port 80 is also open. We can expand the scanning range, but its speed is very slow.

3. Multithreaded scanning

The multi-threaded threading module is introduced to realize multi-threaded scanning. At this time, we only display the open ports.

import telnetlib
import threading
import queue

#IP port development detection
def get_ip_status(ip):
    server = telnetlib.Telnet()
    for port in range(20,10000):
            print('{0} port {1} is open'.format(ip, port))
        except Exception as err:
            #print('{0} port {1} is not open'.format(ip,port))
def check_open(q):
        while True:
            ip = q.get_nowait()
    except queue.Empty as e:

#Main function
if __name__ == '__main__':
    host = ['210.40.xx.xx']     #Analog multiple IP addresses
    q = queue.Queue()
    for ip in host:
    threads = []
    for i in range(10):
        t = threading.Thread(target=check_open,args=(q,))
    for t in threads:

5, Queue realizes C-segment scanning

Although threading solves the problem of controllable thread number, it still can not solve complex problems, such as producer and consumer problems.

Producer consumer questions and Queue module:

  • Queue modules: qsize(), empty(), full(), put(), get()
  • Perfect match: Queue+Thread

Producer and consumer issues

The producer produces goods and puts them into the queue data. When the producer produces these goods, its time is uncertain; When survivors deliver goods to consumers, the time consumed is also uncertain; Due to the uncertainty of both times, there are some problems in multithreaded programming. The queue module is introduced here to solve this problem (Python 3 is queue and python 2 is queue).

The output results are as follows:

The producer uses the Queue to put all data goods into the Queue in order, and then the consumer takes out the data in the Queue in turn. Then C-segment scanning is realized.

# -*- coding: utf-8 -*-
# By:CSDN Eastmount 2019-10-05
import threading
import queue
import sys
from subprocess import Popen, PIPE

#Define a class to pass in the parameter queue
class DoRun(threading.Thread):
    def __init__(self, queue):
        self._queue = queue

    def run(self):
        #Non null data
        while not self._queue.empty():
            ip = self._queue.get()
            #print ip
            check_ping = Popen("ping {0} \n".format(ip), 
                stdin=PIPE, stdout=PIPE,  shell=True)
            data = check_ping.stdout.read()
            data = data.decode("gbk")
            if 'TTL' in data:
                sys.stdout.write(ip+' is UP.\n')
def main():
    threads = []
    threads_count = 100
    q = queue.Queue()
    #Put in ip address
    for i in range(1, 255):
        q.put('210.40.81.' + str(i))

    for i in range(threads_count):

    for i in threads:

    for i in threads:

if __name__ == '__main__':

The final output result is shown in the figure below. The code can detect the survival of the ip segment of a website.

6, Summary

I hope this article will help you. This is the third blog of Python attack and defense. It has programmed and implemented IP and port scanners and multithreaded C-segment scanners. Follow up authors will also continue to study in depth and make some common gadgets for everyone to communicate. Of course, you can also compare with tools such as NMAP, but Python sometimes allows you to integrate stronger and free tools.

The reference article is as follows. Thank these big guys.

  • Analysis of Web penetration technology and practical cases on the road to security, Mr. Chen
  • "Python stunt using Python to become a hacker" teacher Connor
  • https://www.bilibili.com/video/av29479068
  • https://www.bilibili.com/video/av57850011
  • https://www.cnblogs.com/dachenzi/p/8676104.html

Posted on Fri, 03 Dec 2021 08:45:51 -0500 by theironchef