我正在尝试将python客户端(paho-mqtt 1.5.0
)连接到mosquitto代理(自签名证书)。使用MQTT.fx和TLS证书进行连接有效。
但是,当我尝试使用带有此代码(full code)的python客户端进行连接时
mqtt_client.username_pw_set(mqtt_username, password=mqtt_password)
mqtt_client.on_connect = on_connect
mqtt_client.on_publish = on_publish
mqtt_client.tls_set(ca_certs=TLS_CA_CERT, certfile=TLS_CLIENT_CERT,
keyfile=TLS_CLIENT_KEY, cert_reqs=ssl.CERT_REQUIRED,
tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
mqtt_client.tls_insecure_set(False)
mqtt_client.connect(broker_endpoint, port=port)
mqtt_client.loop_start()
我遇到以下错误
Traceback (most recent call last):
File "device.py", line 99, in <module>
main()
File "device.py", line 88, in main
if not connect(mqtt_client, MQTT_USERNAME,
File "device.py", line 55, in connect
mqtt_client.connect(broker_endpoint, port=port)
File "/usr/local/lib/python3.8/site-packages/paho/mqtt/client.py", line 937, in connect
return self.reconnect()
File "/usr/local/lib/python3.8/site-packages/paho/mqtt/client.py", line 1100, in reconnect
sock.do_handshake()
File "/usr/local/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1108)
来自经纪人的日志
1586374114: New connection from 20.4.32.278 on port 8883.
1586374114: OpenSSL Error[0]: error:14035418:SSL routines:ACCEPT_SR_CERT:tlsv1 alert unknown ca
1586374114: OpenSSL Error[1]: error:140350E5:SSL routines:ACCEPT_SR_CERT:ssl handshake failure
1586374114: Socket error on client <unknown>, disconnecting.
根据this问题,我更改了代码
mqtt_client.tls_set(ca_certs=TLS_CA_CERT, certfile=TLS_CLIENT_CERT,
keyfile=TLS_CLIENT_KEY, cert_reqs=ssl.CERT_NONE,
tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
mqtt_client.tls_insecure_set(True)
有了这个我就可以连接到经纪人。但是脚本的第一次尝试失败
Traceback (most recent call last):
File "device.py", line 99, in <module>
main()
File "device.py", line 88, in main
if not connect(mqtt_client, MQTT_USERNAME,
File "device.py", line 55, in connect
mqtt_client.connect(broker_endpoint, port=port)
File "/usr/local/lib/python3.8/site-packages/paho/mqtt/client.py", line 937, in connect
return self.reconnect()
File "/usr/local/lib/python3.8/site-packages/paho/mqtt/client.py", line 1100, in reconnect
sock.do_handshake()
File "/usr/local/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
OSError: [Errno 0] Error
我在布罗克方面看到此错误
1586379530: New connection from 20.4.32.278 on port 1883.
1586379530: Client <unknown> disconnected due to protocol error.
第二次尝试不更改脚本,并且客户端在端口上连接
1586379710: New connection from 20.4.32.278 on port 8883.
1586379710: New client connected from 20.4.32.278 as auto-697CC441-83F5-7F50-6DF8-E85F96DEA1D7 (p2, c1, k60, u'.device.dev.lightcloud.com').
试图理解为什么客户端第一次在端口1883
上连接而失败,然后第二次在端口8883
上连接并成功的原因。
使用cert_reqs=ssl.CERT_NONE
和tls_insecure_set(True)
的客户是否可以完全确保与经纪人的联系?在非生产环境中使用它是否安全?