我想使用Python来监控使用HTTPS的网站。 问题是网站上的证书无效。 我不在乎,我只是想知道该网站正在运行。
我的工作代码如下:
[UIscreen mainscreen].bounds
以URLError结束调用。错误代码为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:
print(e.args)
else:
print ('website ok')
所以,我试图将代码645除外。我试过这个:
C:\python>python monitor443.py
(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c: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')
如何添加此例外?
答案 0 :(得分: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 :(得分: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')