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

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

    For me the examples above would hang if the port wasn't open. Line 4 shows use of settimeout to prevent hanging

    import socket
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(2)                                      #2 Second Timeout
    result = sock.connect_ex(('127.0.0.1',80))
    if result == 0:
      print 'port OPEN'
    else:
      print 'port CLOSED, connect_ex returned: '+str(result)
    

提交回复
热议问题