0

我在使用以下脚本时遇到问题,我正在关注当前的 AWS 教程

https://aws.amazon.com/pt/blogs/big-data/build-a-visualization-and-monitoring-dashboard-for-iot-data-with-amazon-kinesis-analytics-and-amazon-quicksight/

并在我的机器上运行代码 sbs.py:

import json
import random
import datetime
import boto3
import time

deviceNames = ['SBS01', 'SBS02', 'SBS03', 'SBS04', 'SBS05']

iot = boto3.client('iot-data', 'eu-west-2')

# generate Flow values
def getFlowValues():
    data = {}
    data['deviceValue'] = random.randint(60, 100)
    data['deviceParameter'] = 'Flow'
    data['deviceId'] = random.choice(deviceNames)
    data['dateTime'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return data

# generate Temperature values
def getTemperatureValues():
    data = {}
    data['deviceValue'] = random.randint(15, 35)
    data['deviceParameter'] = 'Temperature'
    data['deviceId'] = random.choice(deviceNames)
    data['dateTime'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return data

# generate Humidity values
def getHumidityValues():
    data = {}
    data['deviceValue'] = random.randint(50, 90)
    data['deviceParameter'] = 'Humidity'
    data['deviceId'] = random.choice(deviceNames)
    data['dateTime'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return data

# generate Sound values
def getSoundValues():
    data = {}
    data['deviceValue'] = random.randint(100, 140)
    data['deviceParameter'] = 'Sound'
    data['deviceId'] = random.choice(deviceNames)
    data['dateTime'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return data

# Generate each parameter's data input in varying proportions
while True:
    time.sleep(1)
    rnd = random.random()
    if (0 <= rnd < 0.20):
        data = json.dumps(getFlowValues())
        print(data)
        response = iot.publish(
             topic='/sbs/devicedata/flow',
             payload=data
        ) 
    elif (0.20<= rnd < 0.55):
        data = json.dumps(getTemperatureValues())
        print(data)
        response = iot.publish(
             topic='/sbs/devicedata/temperature',
             payload=data
        )
    elif (0.55<= rnd < 0.70):
        data = json.dumps(getHumidityValues())
        print(data)
        response = iot.publish(
             topic='/sbs/devicedata/humidity',
             payload=data
        )
    else:
        data = json.dumps(getSoundValues())
        print(data)
        response = iot.publish(
             topic='/sbs/devicedata/sound',
             payload=data     
)

我收到以下错误:

{"deviceValue": 21, "deviceParameter": "Temperature", "deviceId": "SBS04", "dateTime": "2021-01-05 10:36:37"}
---------------------------------------------------------------------------
SSLCertVerificationError                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    698             # Make the request on the httplib connection object.
--> 699             httplib_response = self._make_request(
    700                 conn,

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    381         try:
--> 382             self._validate_conn(conn)
    383         except (SocketTimeout, BaseSSLError) as e:

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\connectionpool.py in _validate_conn(self, conn)
   1009         if not getattr(conn, "sock", None):  # AppEngine might not have  `.sock`
-> 1010             conn.connect()
   1011 

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\connection.py in connect(self)
    410 
--> 411         self.sock = ssl_wrap_socket(
    412             sock=conn,

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\util\ssl_.py in ssl_wrap_socket(sock, keyfile, certfile, cert_reqs, ca_certs, server_hostname, ssl_version, ciphers, ssl_context, ca_cert_dir, key_password, ca_cert_data, tls_in_tls)
    427     if send_sni:
--> 428         ssl_sock = _ssl_wrap_socket_impl(
    429             sock, context, tls_in_tls, server_hostname=server_hostname

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\util\ssl_.py in _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname)
    471     if server_hostname:
--> 472         return ssl_context.wrap_socket(sock, server_hostname=server_hostname)
    473     else:

C:\ProgramData\Anaconda3\envs\pythonProject\lib\ssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session)
    499         # ctx._wrap_socket()
--> 500         return self.sslsocket_class._create(
    501             sock=sock,

C:\ProgramData\Anaconda3\envs\pythonProject\lib\ssl.py in _create(cls, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, context, session)
   1039                         raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
-> 1040                     self.do_handshake()
   1041             except (OSError, ValueError):

C:\ProgramData\Anaconda3\envs\pythonProject\lib\ssl.py in do_handshake(self, block)
   1308                 self.settimeout(None)
-> 1309             self._sslobj.do_handshake()
   1310         finally:

SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)

During handling of the above exception, another exception occurred:

SSLError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\httpsession.py in send(self, request)
    253             request_target = self._get_request_target(request.url, proxy_url)
--> 254             urllib_response = conn.urlopen(
    255                 method=request.method,

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    754 
--> 755             retries = retries.increment(
    756                 method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
    505             # Disabled, indicate to re-raise the error.
--> 506             raise six.reraise(type(error), error, _stacktrace)
    507 

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\packages\six.py in reraise(tp, value, tb)
    733             if value.__traceback__ is not tb:
--> 734                 raise value.with_traceback(tb)
    735             raise value

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    698             # Make the request on the httplib connection object.
--> 699             httplib_response = self._make_request(
    700                 conn,

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    381         try:
--> 382             self._validate_conn(conn)
    383         except (SocketTimeout, BaseSSLError) as e:

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\connectionpool.py in _validate_conn(self, conn)
   1009         if not getattr(conn, "sock", None):  # AppEngine might not have  `.sock`
-> 1010             conn.connect()
   1011 

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\connection.py in connect(self)
    410 
--> 411         self.sock = ssl_wrap_socket(
    412             sock=conn,

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\util\ssl_.py in ssl_wrap_socket(sock, keyfile, certfile, cert_reqs, ca_certs, server_hostname, ssl_version, ciphers, ssl_context, ca_cert_dir, key_password, ca_cert_data, tls_in_tls)
    427     if send_sni:
--> 428         ssl_sock = _ssl_wrap_socket_impl(
    429             sock, context, tls_in_tls, server_hostname=server_hostname

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\urllib3\util\ssl_.py in _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname)
    471     if server_hostname:
--> 472         return ssl_context.wrap_socket(sock, server_hostname=server_hostname)
    473     else:

C:\ProgramData\Anaconda3\envs\pythonProject\lib\ssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session)
    499         # ctx._wrap_socket()
--> 500         return self.sslsocket_class._create(
    501             sock=sock,

C:\ProgramData\Anaconda3\envs\pythonProject\lib\ssl.py in _create(cls, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, context, session)
   1039                         raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
-> 1040                     self.do_handshake()
   1041             except (OSError, ValueError):

C:\ProgramData\Anaconda3\envs\pythonProject\lib\ssl.py in do_handshake(self, block)
   1308                 self.settimeout(None)
-> 1309             self._sslobj.do_handshake()
   1310         finally:

SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)

During handling of the above exception, another exception occurred:

SSLError                                  Traceback (most recent call last)
<ipython-input-22-9e04aec45dfe> in <module>
     64         data = json.dumps(getTemperatureValues())
     65         print (data)
---> 66         response = iot.publish(
     67              topic='/sbs/devicedata/temperature',
     68              payload=data

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\client.py in _api_call(self, *args, **kwargs)
    355                     "%s() only accepts keyword arguments." % py_operation_name)
    356             # The "self" in this scope is referring to the BaseClient.
--> 357             return self._make_api_call(operation_name, kwargs)
    358 
    359         _api_call.__name__ = str(py_operation_name)

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\client.py in _make_api_call(self, operation_name, api_params)
    660             http, parsed_response = event_response
    661         else:
--> 662             http, parsed_response = self._make_request(
    663                 operation_model, request_dict, request_context)
    664 

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\client.py in _make_request(self, operation_model, request_dict, request_context)
    680     def _make_request(self, operation_model, request_dict, request_context):
    681         try:
--> 682             return self._endpoint.make_request(operation_model, request_dict)
    683         except Exception as e:
    684             self.meta.events.emit(

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\endpoint.py in make_request(self, operation_model, request_dict)
    100         logger.debug("Making request for %s with params: %s",
    101                      operation_model, request_dict)
--> 102         return self._send_request(request_dict, operation_model)
    103 
    104     def create_request(self, params, operation_model=None):

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\endpoint.py in _send_request(self, request_dict, operation_model)
    134         success_response, exception = self._get_response(
    135             request, operation_model, context)
--> 136         while self._needs_retry(attempts, operation_model, request_dict,
    137                                 success_response, exception):
    138             attempts += 1

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\endpoint.py in _needs_retry(self, attempts, operation_model, request_dict, response, caught_exception)
    251             service_id,
    252             operation_model.name)
--> 253         responses = self._event_emitter.emit(
    254             event_name, response=response, endpoint=self,
    255             operation=operation_model, attempts=attempts,

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\hooks.py in emit(self, event_name, **kwargs)
    354     def emit(self, event_name, **kwargs):
    355         aliased_event_name = self._alias_event_name(event_name)
--> 356         return self._emitter.emit(aliased_event_name, **kwargs)
    357 
    358     def emit_until_response(self, event_name, **kwargs):

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\hooks.py in emit(self, event_name, **kwargs)
    226                  handlers.
    227         """
--> 228         return self._emit(event_name, kwargs)
    229 
    230     def emit_until_response(self, event_name, **kwargs):

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\hooks.py in _emit(self, event_name, kwargs, stop_on_response)
    209         for handler in handlers_to_call:
    210             logger.debug('Event %s: calling handler %s', event_name, handler)
--> 211             response = handler(**kwargs)
    212             responses.append((handler, response))
    213             if stop_on_response and response is not None:

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\retryhandler.py in __call__(self, attempts, response, caught_exception, **kwargs)
    181 
    182         """
--> 183         if self._checker(attempts, response, caught_exception):
    184             result = self._action(attempts=attempts)
    185             logger.debug("Retry needed, action of: %s", result)

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\retryhandler.py in __call__(self, attempt_number, response, caught_exception)
    248 
    249     def __call__(self, attempt_number, response, caught_exception):
--> 250         should_retry = self._should_retry(attempt_number, response,
    251                                           caught_exception)
    252         if should_retry:

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\retryhandler.py in _should_retry(self, attempt_number, response, caught_exception)
    275             # If we've exceeded the max attempts we just let the exception
    276             # propogate if one has occurred.
--> 277             return self._checker(attempt_number, response, caught_exception)
    278 
    279 

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\retryhandler.py in __call__(self, attempt_number, response, caught_exception)
    314     def __call__(self, attempt_number, response, caught_exception):
    315         for checker in self._checkers:
--> 316             checker_response = checker(attempt_number, response,
    317                                        caught_exception)
    318             if checker_response:

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\retryhandler.py in __call__(self, attempt_number, response, caught_exception)
    220             return self._check_response(attempt_number, response)
    221         elif caught_exception is not None:
--> 222             return self._check_caught_exception(
    223                 attempt_number, caught_exception)
    224         else:

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\retryhandler.py in _check_caught_exception(self, attempt_number, caught_exception)
    357         # the MaxAttemptsDecorator is not interested in retrying the exception
    358         # then this exception just propogates out past the retry code.
--> 359         raise caught_exception

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\endpoint.py in _do_get_response(self, request, operation_model)
    198             http_response = first_non_none_response(responses)
    199             if http_response is None:
--> 200                 http_response = self._send(request)
    201         except HTTPClientError as e:
    202             return (None, e)

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\endpoint.py in _send(self, request)
    267 
    268     def _send(self, request):
--> 269         return self.http_session.send(request)
    270 
    271 

C:\ProgramData\Anaconda3\envs\pythonProject\lib\site-packages\botocore\httpsession.py in send(self, request)
    279             return http_response
    280         except URLLib3SSLError as e:
--> 281             raise SSLError(endpoint_url=request.url, error=e)
    282         except (NewConnectionError, socket.gaierror) as e:
    283             raise EndpointConnectionError(endpoint_url=request.url, error=e)

SSLError: SSL validation failed for https://data.iot.eu-west-2.amazonaws.com/topics/%2Fsbs%2Fdevicedata%2Ftemperature [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)

我已经创建并检查了我的 aws 凭证 access_key 和 secret_access_key 是否正常工作。我可以从 cmd 访问我的 s3 存储桶。我知道本地证书或其他问题存在问题,但我不清楚这些问题,因此我不明白我的问题。

我是否必须iot在代码行中输入凭据?我认为它需要读取证书,这些证书是我从我的 aws 管理控制台的 aws 安全凭证创建和下载的 .pem 文件。但我不确定将 .pem 文件放在哪里。

感谢您的帮助!

4

1 回答 1

0

我解决了。

对于那些感兴趣的人,只需在代码的开头插入:`

from botocore.exceptions import ClientError

它应该工作。

最好的。

于 2021-01-07T18:21:10.767 回答