2017-05-28 28 views
0

我是Python的新手(截至上週),我仍然在掌握基本知識,所以請原諒我的任何無知。Python:檢索當前機器上的套接字列表?

作爲我家庭作業的一部分,我被要求製作一個基本的端口掃描儀,其中一個功能是檢索當前機器上的套接字列表。我一直在四處尋找,並設法拼湊一段代碼,允許我輸入希望掃描的機器的IP地址,但我想嘗試一下,以便自動掃描正在運行的計算機。

elif (userChoice == "4"): 

    print("You selected " + userChoice) 

    try: 

     s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # s will be equal to the command looking for the IPV4 addresses 

    except socket.error: 

     sys.exit("Failed to create socket.") # error handling message to be printed to the console should a socket failed to be created 

    print("Socket created") 

    hostAddress = input("Please enter host address to scan - example 'www.server.com': ") 
    print ("You entered " + hostAddress) 

    try: 
     remoteIP = socket.gethostbyname(hostAddress) 

    except socket.gaierror: 

      sys.exit("Hostname could not be resolved exiting") 

      ret = input("Hit return to go back to the menu") 

      continue 

    print("IP address of " + hostAddress + ' is ' + remoteIP) 

這是我的代碼到目前爲止。如果任何人都可以幫助我,或者告訴我是否我正在朝着正確的方向前進,我會非常感激。

此外,我作爲一個noob,如果任何人有任何好的閱讀材料的建議,以幫助我去掌握基本知識,我將非常感激。

謝謝。

+0

'hostAddress = 'localhost''或替代地'hostAddress =' 127.0.0.1''? –

回答

0

要檢查遠程服務器 - 開放端口

# For input hostAddress 
remoteIP = socket.gethostbyname(hostAddress) 
for port in range(1,1025): 
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
     result = sock.connect_ex((remoteIP, port)) 
     if result == 0: 
      print("Port %s: Open"%port) 
     sock.close() 

=> Port 80: Open