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

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

    If you want to use this in a more general context, you should make sure, that the socket that you open also gets closed. So the check should be more like this:

    import socket
    from contextlib import closing
    
    def check_socket(host, port):
        with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
            if sock.connect_ex((host, port)) == 0:
                print "Port is open"
            else:
                print "Port is not open"
    

提交回复
热议问题