Implement a most basic port scanner with python

A port scanner is a tool that detects whether a server or host virtual port is open or closed.

The principle is that the program tries to establish a connection with the target host. If the target host responds, the port is open.

Use python to write a port scanner

There are roughly two ways to determine whether the port is open

method one:

s = socket.socket()
s.connect((‘ip, port))
result_code= s.recv(1024)

Way two:

s = socket.socket()
result_code = s.connect_ex((ip, port))

Here I used the second method to implement the port scanner

code show as below:

import socket
import sys

def portscan(ip):
    PORT_OPEN_MSG = "%6d [OPEN]"
    PORT_CLOSE_MSG = "%6d [CLOSE]"
    result_list = list()
    port_list = [21,22,25,53,80,110,113,135,139,143,179,199,443,445,465,514,548,554,587,646,993,995,1025,1026,1433,1720,1723,2000,3306,3389,5060,5666,5900,6001,8000,8008,8080,8443,8888,10000,32768,49152,49154] #扫描所有端口太浪费时间,所以选择一个要扫描的端口列表进行扫描
    for port in port_list:
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(0.1)
            result_code = s.connect_ex((ip, port))
            if result_code == 0:
                print(PORT_OPEN_MSG % port)
                result_list.append(port)
            else:
                print(PORT_CLOSE_MSG % port)
                result_list.append(port)
        except Exception as e:
            print(e)
        finally:
            s.close()
    return result_list

def main():
    if len(sys.argv) > 1:
         portscan(sys.argv[1])
    else:
        print("param less")
if __name__ == '__main__':
    main()

The operation effect is as follows:

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44001905/article/details/109203997