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

前端 未结 12 1009
半阙折子戏
半阙折子戏 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:37

    Just added to mrjandro's solution a quick hack to get rid of simple connection errors / timeouts.

    You can adjust the threshold changing max_error_count variable value and add notifications of any sort.

    import socket
    
    max_error_count = 10
    
    def increase_error_count():
        # Quick hack to handle false Port not open errors 
        with open('ErrorCount.log') as f:
            for line in f:
                error_count = line
        error_count = int(error_count)
        print "Error counter: " + str(error_count)
        file = open('ErrorCount.log', 'w')
        file.write(str(error_count + 1))
        file.close()
        if error_count == max_error_count:
            # Send email, pushover, slack or do any other fancy stuff
            print "Sending out notification"
            # Reset error counter so it won't flood you with notifications
            file = open('ErrorCount.log', 'w')
            file.write('0')
            file.close()
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(2) 
    result = sock.connect_ex(('127.0.0.1',80))
    if result == 0:
            print "Port is open"
    else:
            print "Port is not open"
            increase_error_count()
    

    And here you find a Python 3 compatible version (just fixed print syntax):

    import socket
    
    max_error_count = 10
    
    def increase_error_count():
        # Quick hack to handle false Port not open errors
        with open('ErrorCount.log') as f:
            for line in f:
                error_count = line
        error_count = int(error_count)
        print ("Error counter: " + str(error_count))
        file = open('ErrorCount.log', 'w')
        file.write(str(error_count + 1))
        file.close()
        if error_count == max_error_count:
            # Send email, pushover, slack or do any other fancy stuff
            print ("Sending out notification")
            # Reset error counter so it won't flood you with notifications
            file = open('ErrorCount.log', 'w')
            file.write('0')
            file.close()
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(2) 
    result = sock.connect_ex(('127.0.0.1',80))
    if result == 0:
            print ("Port is open")
    else:
            print ("Port is not open")
            increase_error_count()
    

提交回复
热议问题