Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何使用.p12证书对rest api进行身份验证_Python 3.x_Api_Post_Python Requests_P12 - Fatal编程技术网

Python 3.x 如何使用.p12证书对rest api进行身份验证

Python 3.x 如何使用.p12证书对rest api进行身份验证,python-3.x,api,post,python-requests,p12,Python 3.x,Api,Post,Python Requests,P12,我已收到带有用户名和密码的证书。p12。 在系统中安装此证书后,我可以使用Rest客户端进行post请求。 如何使用此证书使用Python请求方法对Rest API上的post请求进行身份验证? 我正在使用下面的代码,但它不工作 import requests headers = {'Content-Type': 'application/json'} payload = {'folder': '/Trial/trial_dir'} response = requests.post('https

我已收到带有用户名和密码的证书。p12。
在系统中安装此证书后,我可以使用Rest客户端进行post请求。
如何使用此证书使用Python请求方法对Rest API上的post请求进行身份验证?
我正在使用下面的代码,但它不工作

import requests
headers = {'Content-Type': 'application/json'}
payload = {'folder': '/Trial/trial_dir'}
response = requests.post('https://<IP>:8080/siteapi/availabletests', params=payload, headers=headers, verify='C:\\Users\\ukhare\\Desktop\\sigos\\cert.p12', auth=('trial_test','trialtest'))
导入请求
headers={'Content-Type':'application/json'}
有效负载={'folder':'/Trial/Trial_dir'}
response=requests.post('https://:8080/siteapi/availabletests',params=payload,headers=headers,verify='C:\\Users\\ukhare\\Desktop\\sigos\\cert.p12',auth=('trial\u test','trialtest'))
下面是一个错误:

Traceback (most recent call last):
  File "D:\m\Python34\lib\site-packages\urllib3\connection.py", line 171, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw)
  File "D:\m\Python34\lib\site-packages\urllib3\util\connection.py", line 79, in create_connection
    raise err
  File "D:\m\Python34\lib\site-packages\urllib3\util\connection.py", line 69, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "D:\m\Python34\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
        chunked=chunked)
      File "D:\m\Python34\lib\site-packages\urllib3\connectionpool.py", line 343, in _make_request
        self._validate_conn(conn)
      File "D:\m\Python34\lib\site-packages\urllib3\connectionpool.py", line 849, in _validate_conn
        conn.connect()
      File "D:\m\Python34\lib\site-packages\urllib3\connection.py", line 314, in connect
        conn = self._new_conn()
      File "D:\m\Python34\lib\site-packages\urllib3\connection.py", line 180, in _new_conn
        self, "Failed to establish a new connection: %s" % e)
    urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x036B0230>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "D:\m\Python34\lib\site-packages\requests\adapters.py", line 445, in send
        timeout=timeout
      File "D:\m\Python34\lib\site-packages\urllib3\connectionpool.py", line 638, in urlopen
        _stacktrace=sys.exc_info()[2])
      File "D:\m\Python34\lib\site-packages\urllib3\util\retry.py", line 398, in increment
        raise MaxRetryError(_pool, url, error or ResponseError(cause))
    urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='IP', port=8080): Max retries exceeded with url: /siteapi/availabletests?folder=%2FTrial%2Ftrial_dir (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x036B0230>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "D:\m\Python34\lib\site-packages\requests\api.py", line 112, in post
        return request('post', url, data=data, json=json, **kwargs)
      File "D:\m\Python34\lib\site-packages\requests\api.py", line 58, in request
        return session.request(method=method, url=url, **kwargs)
      File "D:\m\Python34\lib\site-packages\requests\sessions.py", line 512, in request
        resp = self.send(prep, **send_kwargs)
      File "D:\m\Python34\lib\site-packages\requests\sessions.py", line 622, in send
        r = adapter.send(request, **kwargs)
      File "D:\m\Python34\lib\site-packages\requests\adapters.py", line 513, in send
        raise ConnectionError(e, request=request)
    requests.exceptions.ConnectionError: HTTPSConnectionPool(host='IP', port=8080): Max retries exceeded with url: /siteapi/availabletests?folder=%2FTrial%2Ftrial_dir (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x036B0230>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))
回溯(最近一次呼叫最后一次):
文件“D:\m\Python34\lib\site packages\urllib3\connection.py”,第171行,位于康涅狄格州的新
(self.\u dns\u主机、self.port)、self.timeout、**额外功率)
文件“D:\m\Python34\lib\site packages\urllib3\util\connection.py”,第79行,位于create\u connection中
提出错误
文件“D:\m\Python34\lib\site packages\urllib3\util\connection.py”,第69行,位于create\u connection中
sock.connect(sa)
ConnectionRefusedError:[WinError 10061]无法建立连接,因为目标计算机主动拒绝了它
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“D:\m\Python34\lib\site packages\urllib3\connectionpool.py”,第600行,在urlopen中
分块=分块)
文件“D:\m\Python34\lib\site packages\urllib3\connectionpool.py”,第343行,在请求中
自我验证连接(连接)
文件“D:\m\Python34\lib\site packages\urllib3\connectionpool.py”,第849行,在\u validate\u conn中
连接
文件“D:\m\Python34\lib\site packages\urllib3\connection.py”,第314行,在connect中
conn=自我。_new_conn()
文件“D:\m\Python34\lib\site packages\urllib3\connection.py”,第180行,位于康涅狄格州的新州
self,“无法建立新连接:%s”%e)
urllib3.exceptions.NewConnectionError::未能建立新连接:[WinError 10061]无法建立连接,因为目标计算机主动拒绝它
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“D:\m\Python34\lib\site packages\requests\adapters.py”,第445行,在send中
超时=超时
文件“D:\m\Python34\lib\site packages\urllib3\connectionpool.py”,第638行,在urlopen中
_stacktrace=sys.exc_info()[2])
文件“D:\m\Python34\lib\site packages\urllib3\util\retry.py”,第398行,增量
引发MaxRetryError(_池、url、错误或响应错误(原因))
urllib3.exceptions.MaxRetryError:HTTPSConnectionPool(host='IP',port=8080):url:/siteapi/availabletests?文件夹=%2FTRIT%2FTRIT_dir超过了最大重试次数(由NewConnectionError错误引起(':未能建立新连接:[WinError 10061]无法建立连接,因为目标计算机主动拒绝它',))
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“D:\m\Python34\lib\site packages\requests\api.py”,第112行,在post中
返回请求('post',url,data=data,json=json,**kwargs)
文件“D:\m\Python34\lib\site packages\requests\api.py”,第58行,在请求中
return session.request(method=method,url=url,**kwargs)
请求中第512行的文件“D:\m\Python34\lib\site packages\requests\sessions.py”
resp=自我发送(准备,**发送)
文件“D:\m\Python34\lib\site packages\requests\sessions.py”,第622行,在send中
r=适配器.send(请求,**kwargs)
文件“D:\m\Python34\lib\site packages\requests\adapters.py”,第513行,在send中
raise ConnectionError(e,请求=请求)
requests.exceptions.ConnectionError:HTTPSConnectionPool(host='IP',port=8080):url:/siteapi/availabletests?文件夹=%2FTRITY%2FTRITY\U dir超过了最大重试次数(由NewConnectionError引起(':未能建立新连接:[WinError 10061]无法建立连接,因为目标计算机主动拒绝了它',))
参考:

我用的是有效载荷

data={"folder": "/Trial/trial_dir"}
哪一个是字典,而它应该是字典的正确字符串

data='{"folder": "/Trial/trial_dir"}'
因此,以下是使用python成功发布请求的结果:-

  • Header参数应该是字典
  • e、 g

  • 数据参数应该是字符串格式的字典
  • e、 g

    data='{"folder": "/Trial/trial_dir"}'
    
  • 验证应设置为False:
    Verify=False
    以忽略验证SSL证书
  • 以下是从我提出的请求中收到的状态和内容:

    >>> import json
    >>> from requests_pkcs12 import get,post
    >>> url = 'https://IP:8080/siteapi/availabletests'
    >>> pkcs12_filename = 'C:\\Users\\ukhare\\Desktop\\tests\\trial_tata.p12'
    >>> pkcs12_password = 'trialtest'
    >>> response = post(url, data='{"folder": "/Trial/trial_dir"}', headers={'Content-Type': 'application/json'}, verify=False, pkcs12_filename=pkcs12_filename,pkcs12_password=pkcs12_password)
    
    
    D:\m\Python34\lib\site-packages\urllib3\connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
      InsecureRequestWarning)
    >>> print(response.status_code)
    200
    >>> print(json.dumps(json.loads(response.content.decode("utf-8")), indent=4, separators=(',', ': '), sort_keys=True))
    {
        "availableTests": [
            "/Trial/trial_test/HTTP_Download"
        ],
        "serviceError": null
    

    只是想说明你在使用请求库,对吗?@Fozoro:是的,我在使用请求库。有什么线索我可以使用p12证书发布使用请求的东西。发布什么时候必须使用用户名和密码?你能发布你当前的证书吗code@Fozoro:我刚刚添加了我的代码并追溯到问题所在。请尝试将
    verify=
    替换为
    cert=
    >>> import json
    >>> from requests_pkcs12 import get,post
    >>> url = 'https://IP:8080/siteapi/availabletests'
    >>> pkcs12_filename = 'C:\\Users\\ukhare\\Desktop\\tests\\trial_tata.p12'
    >>> pkcs12_password = 'trialtest'
    >>> response = post(url, data='{"folder": "/Trial/trial_dir"}', headers={'Content-Type': 'application/json'}, verify=False, pkcs12_filename=pkcs12_filename,pkcs12_password=pkcs12_password)
    
    
    D:\m\Python34\lib\site-packages\urllib3\connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
      InsecureRequestWarning)
    >>> print(response.status_code)
    200
    >>> print(json.dumps(json.loads(response.content.decode("utf-8")), indent=4, separators=(',', ': '), sort_keys=True))
    {
        "availableTests": [
            "/Trial/trial_test/HTTP_Download"
        ],
        "serviceError": null