首页 > 解决方案 > 通过 Python 发布 MQTT:[Errno 101] 网络不可达

问题描述

我已经使用此脚本在本地网络中的 MQTT 代理上测试了我的脚本:

import paho.mqtt.publish as publish

publish.single('some_topic, 'some message', hostname="192.168.1.123")

一切正常。现在我想发布到我获得凭据的实际服务器。遗憾的是,paho MQTT 脚本的所有示例都发布到本地服务器,因此我无法真正模拟我的脚本。我提供的凭据包括用户名、密码和主题。作为“主机名”,我进入了公司服务器的网站。

脚本现在说

import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt

client = mqtt.Client()

client.username_pw_set("given_username",password="given_password")

publish.single("some_topic",'some message',hostname="example.com")

可悲的是,我得到一个错误。

  File "get_datas.py", line 18, in handle_data
    publish.single("some_topic",msg,hostname="example.com")
  File "/usr/local/lib/python3.6/site-packages/paho/mqtt/publish.py", line 223, in single
    protocol, transport)
  File "/usr/local/lib/python3.6/site-packages/paho/mqtt/publish.py", line 159, in multiple
    client.connect(hostname, port, keepalive)
  File "/usr/local/lib/python3.6/site-packages/paho/mqtt/client.py", line 839, in connect
    return self.reconnect()
  File "/usr/local/lib/python3.6/site-packages/paho/mqtt/client.py", line 962, in reconnect
    sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
  File "/usr/local/lib/python3.6/socket.py", line 722, in create_connection
    raise err
  File "/usr/local/lib/python3.6/socket.py", line 713, in create_connection
    sock.connect(sa)
OSError: [Errno 101] Network is unreachable

我写错了吗?

编辑:似乎主机名有问题。我可以通过插入服务器的 IP 地址来解决这个问题,我通过

[11:26:39] $ ping example.com
PING example.com (xx.xxx.xxx.xxx) 56(84) bytes of data.
64 bytes from example.com (xx.xxx.xxx.xxx): icmp_seq=1 ttl=53 time=43.3 ms

标签: pythonmqttpaho

解决方案


  1. 您可能会遗漏在 url 中提及协议部分,例如tcp://website.io. 对于websocket tcpssl应该正确提及。
  2. 还要检查防火墙中的出站流量规则。sudo ufw status添加您允许无处不在的通信协议。

推荐阅读