How to check if a network port is open on linux?

前端 未结 12 1008
半阙折子戏
半阙折子戏 2020-12-07 11:07

How can I know if a certain port is open/closed on linux ubuntu, not a remote system, using python? How can I list these open ports in python?

  • Netstat: Is th
12条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 11:28

    Here's a fast multi-threaded port scanner:

    from time import sleep
    import socket, ipaddress, threading
    
    max_threads = 50
    final = {}
    def check_port(ip, port):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP
            #sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
            socket.setdefaulttimeout(2.0) # seconds (float)
            result = sock.connect_ex((ip,port))
            if result == 0:
                # print ("Port is open")
                final[ip] = "OPEN"
            else:
                # print ("Port is closed/filtered")
                final[ip] = "CLOSED"
            sock.close()
        except:
            pass
    port = 80
    for ip in ipaddress.IPv4Network('192.168.1.0/24'): 
        threading.Thread(target=check_port, args=[str(ip), port]).start()
        #sleep(0.1)
    
    # limit the number of threads.
    while threading.active_count() > max_threads :
        sleep(1)
    
    print(final)
    

    Live Demo

提交回复
热议问题