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

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

    In the Above,I found multiple solutions.But some solutions having a hanging issue or taking to much time in case of the port was not opened.Below solution worked for me :

    import socket 
    
    def port_check(HOST):
       s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
       s.settimeout(2) #Timeout in case of port not open
       try:
          s.connect((HOST, 22)) #Port ,Here 22 is port 
          return True
       except:
          return False
    
    port_check("127.0.1.1")
    

提交回复
热议问题