2016-08-04 64 views
0

我想用Python來監視使用HTTPS的網站。 問題是,網站上的證書無效。 我不在乎,我只是想知道網站正在運行。python capture URLError code

我工作的代碼如下所示:

from urllib.request import Request, urlopen 
from urllib.error import URLError, HTTPError 
req = Request("https://somedomain.com") 

try: 
    response = urlopen(req) 
except HTTPError as e: 
    print('server couldn\'t fulfill the request') 
    print('error code: ', e.code) 
except URLError as e: 
     print(e.args)  
else: 
    print ('website ok') 

,在URLError結束被調用。錯誤代碼是645.

C:\python>python monitor443.py 
(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)'),) 

所以,我試圖除了代碼645以外。我已經試過這樣:

from urllib.request import Request, urlopen 
from urllib.error import URLError, HTTPError 
req = Request("https://somedomain.com") 

try: 
    response = urlopen(req) 
except HTTPError as e: 
    print('server couldn\'t fulfill the request') 
    print('error code: ', e.code) 
except URLError as e: 
     if e.code == 645: 
      print("ok") 
     print(e.args)  
else: 
    print ('website ok') 

,但得到這個錯誤:

Traceback (most recent call last): 
    File "monitor443.py", line 11, in <module> 
    if e.code == 645: 
AttributeError: 'URLError' object has no attribute 'code' 

如何添加此異常?

+0

['URLError'是OSERROR的一個子類(http://stackoverflow.com/q/38773209/344286)可能會說,它是在['e.errno'發現](https://docs.python.org/3/library/exceptions.html#OSError.errno)? –

+0

e.errno返回「none」 – Shawn

+0

另外... 645不是errorno,那是錯誤發生的C源代碼行,AFAIK。 –

回答

1

請看看偉大的requests包。這會在進行http通信時簡化您的生活。見http://requests.readthedocs.io/en/master/

pip install requests 

要跳過證書檢查,你會做這樣的事情(注意verify參數!):

requests.get('https://kennethreitz.com', verify=False) 
<Response [200]> 

查看完整的文檔here

HTH

1

我無法安裝SLL庫(egg_info錯誤)。 這是我最後做

from urllib.request import Request, urlopen 
from urllib.error import URLError, HTTPError 

def sendEmail(r):  
    #send notification 
    print('send notify') 

req = Request("https://somedomain.com") 

try: 
    response = urlopen(req) 
except HTTPError as e: 
    print('server couldn\'t fulfill the request') 
    print('error code: ', e.code) 
    sendEmail('server couldn\'t fulfill the request') 
except URLError as e: 
     theReason=str(e.reason) 
     #[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) 
     if theReason.find('CERTIFICATE_VERIFY_FAILED') == -1: 
      sendEmail(theReason) 
     else: 
      print('website ok')   
else: 
    print('website ok')