如何在paho.mqtt.subscribe中设置username / passwd

时间:2018-03-08 20:58:36

标签: python-3.x mqtt

这是我subscribe_simple.py

的脚本
import paho.mqtt.subscribe as subscribe

topics = ['#']

m = subscribe.simple(topics, hostname="eu.thethings.network", retained=False, msg_count=2)

for a in m:
    print(str(a.topic))
    print(str(a.payload))

将此信息作为错误消息发送给我:

Traceback (most recent call last):
  File "MQTT_subscribe_simple.py", line 15, in <module>
    m = subscribe.simple(topics, hostname="eu.thethings.network", retained=False, msg_count=2)
  File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/subscribe.py", line 252, in simple
    clean_session)
  File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/subscribe.py", line 165, in callback
    client.loop_forever()
  File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line 1481, in loop_forever
    rc = self.loop(timeout, max_packets)
  File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line 1003, in loop
    rc = self.loop_read(max_packets)
  File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line 1284, in loop_read
    rc = self._packet_read()
  File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line 1849, in _packet_read
    rc = self._packet_handle()
  File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line 2311, in _packet_handle
    return self._handle_connack()
  File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line 2372, in _handle_connack
    self.on_connect(self, self._userdata, flags_dict, result)
  File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/subscribe.py", line 29, in _on_connect
    raise mqtt.MQTTException(paho.connack_string(rc))
paho.mqtt.MQTTException: Connection Refused: not authorised.

我把这行放在循环之前,用正确的值

m.username_pw_set(username, password)

没问题

是否可以使用paho.mqtt.subscribe进行身份验证以及如何使用?

1 个答案:

答案 0 :(得分:1)

查看来源here,您可以将auth对象传递给subscribe.simple()来电。

e.g。

m = subscribe.simple(topics, hostname="eu.thethings.network", retained=False, msg_count=2, auth={'username':"foo", 'password':"bar"})