我想確定一個web服務器列表是否正在偵聽與套接字庫的端口。不過,我無法通過列表成功運行迭代:無法迭代字符串列表連接功能與套接字
#!/usr/bin/python
import socket
myList = ['www.google.com', 'www.spoon.com']
scanList = []
port = 80
def resolveHost(x):
try:
h = socket.gethostbyname(x)
except:
pass
return h
def scan(host,port):
s = socket.socket()
s.connect(host,port)
print s.recv(3)
for x in myList:
scanList.append(resolveHost(x))
print scanList
for x in scanList:
scan(x,25)
This is returning:
Traceback (most recent call last):
['216.58.199.196', '207.32.184.61']
File "C:/Users/Casey/Desktop/projects/dsid_check.py", line 28, in <module>
scan(x,25)
File "C:/Users/Casey/Desktop/projects/dsid_check.py", line 18, in scan
s.connect(host,port)
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
TypeError: connect() takes exactly one argument (2 given)
Process finished with exit code 1
我希望看到的是來自這些頁面的響應,但我沒有。
編輯---------- ------------來源
所以我修改我的源看成這樣:
#!/usr/bin/python
import socket
myList = ['www.espn.com', 'www.google.com', 'www.spoon.com']
scanList = []
port = 80
def resolveHost(x):
try:
h = socket.gethostbyname(x)
return h
except:
print "Could not resolve %s" % x
def scan(host,port):
hostR = resolveHost(host)
s = socket.socket()
s.settimeout(3)
s.connect((hostR,port))
try:
print s.recv(1024)
except:
print "Connection to %s timed out" % x
for x in myList:
scanList.append(resolveHost(x))
for x in scanList:
scan(x,port)
有了這個,我無法連接到應該在線的Web服務器列表。現在閱讀Alex推薦的圖書館鏈接。
假設'socket.gethostbyname'提高你忽略一個例外。如何在沒有定義時返回'h'?讓例外提出。 –
您還可以將'scanList'定義爲'[在myList中爲x的resolveHost(x)]'或'map(resolveHost,myList)'。 –