標籤:瀏覽器 request ima 沒有 final end lib 字串 預設
我使用的是python2.7,我本來另裝了一個python3.6,發現無法安裝dnspython,於是只能換回來了
import dns.resolver #這個需要另外下載並安裝(www.dnspython.org/kits/1.9.4/dnspython-1.9.4.tar.gz 解壓之後,python setup.py install)
import os
import httplib #因為要用到http?
iplist=[] #儲存查到的ip
appdomain="www.baidu.com" #查詢的網站伺服器
def get_iplist(domain=""): #這應該是說如果domain沒有值,則預設為空白
try: #捕獲異常
A=dns.resolver.query(domain,‘A‘)
print (‘hi‘)
except Exception,e:
print ‘dns wrong:‘+str(e)
return
for i in A.response.answer:
for j in i.items:
print ("ip is %s " % j)
newj=str(j) #如果不轉換為字串格式,會報錯
#print type(newj)
iplist.append(newj) #把查詢到的ip放到列表中
return True
def checkip(ip): #類比瀏覽器訪問,查詢服務器是否異常
checkurl=ip+‘:80‘
getcontent=""
httplib.socket.setdefaulttimeout(5) #設定預設逾時時間
conn=httplib.HTTPConnection(checkurl)
try:
conn.request("GET","/",headers={"HOST":appdomain}) #擷取標頭檔內容
r=conn.getresponse()
getcontent=r.read(15) #取標頭檔的一部分進行對比即可
print getcontent
finally:
if getcontent=="": #注意,這裡區分大小寫,因為是字串比較
print ip+" [ok]"
else:
print ip+" [error]"
if name=="main":
#if get_iplist(appdomain) and len(iplist)>0:
if get_iplist(appdomain):
for ip in iplist: #逐個檢查
checkip(ip)
else:
print "dns resolver error."
python使用dns輪循檢測web伺服器是否異常