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

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

    Agree with Sachin. Just one improvement, use connect_ex instead of connect, which can avoid try except

    >>> def port_check(ip_port):
    ...     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ...     s.settimeout(1)
    ...     r = s.connect_ex(ip_port)
    ...     return r == 0
    ... 
    >>> port_check(loc)
    True
    >>> port_check(loc_x)
    False
    >>> loc
    ('10.3.157.24', 6443)
    >>> 
    

提交回复
热议问题