Python-调用REST端点时与SSL相关的错误

时间:2018-06-27 10:45:29

标签: python rest ssl ssl-certificate

我创建了一个Python脚本来调用名为“ GetCust”的自定义 REST端点

这是Python脚本:

import sys
from ntlm import HTTPNtlmAuthHandler
import urllib2
import json
import ssl

def get_client(custID):
    user = r'myusername'
    password = 'mypassword'
    passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
    passman.add_password(None, "https://api.xyz.com", user, password)
    auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)
    opener = urllib2.build_opener(auth_NTLM)
    urllib2.install_opener(opener)
    url = "https://api.xyz.com/webservice/api/cust/GetCust/%s" % CustID
    response = urllib2.urlopen(url)
    cust = json.loads(response.read())
    return cust


cust = get_client("1234")
print "CustID: %s" % cust['ReturnValue']['CustID']
print "Name: %s" % cust['ReturnValue']['Name']

在执行此脚本时,出现以下错误:

<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)>

然后,我尝试通过在“响应” 变量的逻辑中进行以下更改来修复此错误:

response = urllib2.urlopen(url, cafile="/home/username/cust/CertName.crt")

我进行了上述更改,以指向证书,因为初始错误(如上所述)似乎与SSL证书问题有关。 我使用来自“ url” 变量的链接下载了证书。

[请注意,此处提到的“ url” 变量值是一个虚拟值。]

所以现在我的脚本如下:

import sys
from ntlm import HTTPNtlmAuthHandler
import urllib2
import json
import ssl

def get_client(custID):
    user = r'myusername'
    password = 'mypassword'
    passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
    passman.add_password(None, "https://api.xyz.com", user, password)
    auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)
    opener = urllib2.build_opener(auth_NTLM)
    urllib2.install_opener(opener)
    url = "https://api.xyz.com/webservice/api/cust/GetCust/%s" % CustID
    response = urllib2.urlopen(url, cafile="/home/username/cust/CertName.crt")
    cust = json.loads(response.read())
    return cust


cust = get_client("1234")
print "CustID: %s" % cust['ReturnValue']['CustID']
print "Name: %s" % cust['ReturnValue']['Name']

但是进行更改后,我现在遇到以下错误:

“unknown error (_ssl.c:2947)”

需要帮助解决此问题。 我目前的方法正确吗?

注意:我也在python虚拟环境中也收到此错误。

0 个答案:

没有答案