【问题标题】:python paho mqtt can not connect to mqtts with username and passwordpython paho mqtt无法使用用户名和密码连接到mqtts
【发布时间】:2020-06-19 23:15:55
【问题描述】:

我的 raspberrypi 上的以下 python 代码没有连接到我的 mqtt 代理,它只是在打印 Connecting... 后挂起:

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("test")


def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))


client = mqtt.Client(client_id="",clean_session=True,userdata=None,protocol=mqtt.MQTTv311,transport="tcp")
client.on_connect = on_connect
client.on_message = on_message

client.username_pw_set(username="stackoverflow",password="stackoverflow")
print("Connecting...")
client.connect("learn.evermight.net", 9101, 10)
client.loop_forever()

我的 Python 代码做错了什么?


命令行成功

我确认我的 mqtt 确实有效,因为我可以使用以下命令从终端订阅:

mosquitto_sub -h learn.evermight.net -p 9101 -t "test" -u "stackoverflow" -P "stackoverflow" --capath /etc/ssl/certs/

一旦我从另一个终端运行此命令,我就会在我的终端中看到消息

mosquitto_pub -h learn.evermight.net -p 9101 -t "test" -u "stackoverflow" -P "stackoverflow" -m "hello world" --capath /etc/ssl/certs/

我的 python 代码有什么问题?


NodeJS 成功

此外,以下 NodeJS 代码也可用于连接和发布到我的 MQTT 服务器。

const mqtt = require('async-mqtt');

  try{
    const client = await mqtt.connectAsync("mqtts://learn.evermight.net",{
      port:9101,
      host:"mqtts://learn.evermight.net",
      username:"stackoverflow",
      password:"stackoverflow",
      connectTimeout:5000,
      protocolId:"MQIsdp",
      protocolVersion:3,
      encoding:"utf8",
      keepalive: 60
    });
    await client.publish("test","hello world");
    await client.end();
  } catch(e) {
    console.log(e);
  }

网站 JavaScript 成功

而且下面的代码也可以通过网页浏览器javascript网站连接到一个websocket端口,订阅test主题并接收发布的消息(注意我的websockets使用端口9102)

import Paho from "paho-mqtt";

const client = new Paho.Client("learn.evermight.net",9102,"WebBrowser");
  client.onConnectionLost = response=>console.log("lostMQTTConnection: " +(response.errorCode !== 0 ? response.errorMessage : "Unknown MQTT Error" ));
  client.onMessageArrived = message=>console.log(message.payloadString);
  client.connect({
    onSuccess:_=>client.subscribe("test"),
    useSSL:true,
    userName:"stackoverflow",
    password:"stackoverflow",
  });

【问题讨论】:

  • 为什么你知道它是否挂起? loop_forever() 应该一直运行代码,直到你杀死它。
  • 对我来说所有问题都可以是--capath /etc/ssl/certs/。当我使用代理运行您的代码时,它会运行,当我运行 mosquitto_pub 而没有 --capath /etc/ssl/certs/ 时,它也会运行,但当我使用 --capath /etc/ssl/certs/ 时,我会得到 Error: Connection refused。可能在代码中你必须使用类似于--capath /etc/ssl/certs/
  • @furas 我更新了我的代码,为我的 mqtt 服务器提供了真实的凭据,并在 bash、nodejs 和纯 JavaScript 中提供了真实的工作示例。唯一失败的是我的python代码。我的服务器是否适用于您的 python 脚本?
  • 它不适用于 Python。它仅适用于mosquitto_sub/mosquitto_pub,因此我可以连接。有命令client.tls_set()client.tls_set_context(),也许他们可以提供帮助。但我从来不用它。我在本地网络中有自己的 MTTQ,所以我懒得使用 certs

标签: python mqtt


【解决方案1】:

我发现如果我添加这个不带参数的命令,我可以连接

client.tls_set()

paho documentation 的描述末尾tls_set() 你可以看到

Must be called before connect*().

但即使在client.connect() 之后它也对我有用


在同一个文档中,您可以看到没有参数它使用默认的系统设置

By default, on Python 2.7.9+ or 3.4+,  
the default certification authority of the system is used. 

On older Python version this parameter is mandatory.

仅当mosquitto_sub/mosquitto_pub 需要--capath /etc/ssl/certs/ 时才需要。
如果mosquitto_sub/mosquitto_pub 在没有--capath /etc/ssl/certs/ 的情况下工作,那么不要使用它。


import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code", rc)
    client.subscribe("test")

def on_message(client, userdata, msg):
    print(msg.topic, msg.payload)


client = mqtt.Client(client_id="", clean_session=True, userdata=None, protocol=mqtt.MQTTv311, transport="tcp")
client.on_connect = on_connect
client.on_message = on_message

client.tls_set()  # <--- even without arguments

client.username_pw_set(username="stackoverflow", password="stackoverflow")
print("Connecting...")
client.connect("learn.evermight.net", 9101, 10)
client.loop_forever()

【讨论】:

  • 成功了!我发现我也可以像这样client=mqtt.Client() 将构造函数留空。只是 client.tls_set() 成功了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 2023-03-22
  • 2022-12-07
  • 1970-01-01
  • 1970-01-01
  • 2022-06-19
  • 1970-01-01
相关资源
最近更新 更多