PythonAnywhere上paho-mqtt连接Beebotte出现认证/连接拒绝问题
Let's break down why you're seeing this connection refused error on PythonAnywhere and how to fix it:
1. PythonAnywhere Blocks Unencrypted MQTT Port (Most Likely Culprit)
PythonAnywhere restricts outbound connections to non-encrypted ports by default. The standard MQTT port 1883 is often blocked, while the encrypted MQTT over TLS port (8883) is allowed. Your local environment doesn't have this restriction, which is why it works there.
Fix: Update your code to use port 8883 and enable TLS encryption:
import paho.mqtt.publish as publish mqtt_host = "beebotte.com" mqtt_topic = "climate/set/livingroom" # Follow Beebotte's standard auth format: username = "token", password = your raw token value auth = {'username': "token", 'password': "token_KxDxlcmXgQBDfWRNC"} # Use your actual token here publish.single( mqtt_topic, "python sent", hostname=mqtt_host, port=8883, # Use encrypted port auth=auth, tls={'ca_certs': None} # Leverage default system CA certificates )
2. Incorrect Token Authentication Format
From your note about token formats (token:token_KxDxlcmXgQBDfWRNC), Beebotte's MQTT authentication expects:
- Username:
"token"(the literal string, not including your token value) - Password: Your raw token string (e.g.,
token_KxDxlcmXgQBDfWRNC, without thetoken:prefix)
Your original code passed the full token:MY_SECRET_TOKEN as the username, which doesn't align with Beebotte's auth rules. This mismatch can cause authentication failures, which manifest as connection refused errors.
3. Paho-MQTT Version Discrepancies
While Python 2.7.6 vs 2.7.13 is unlikely to be the direct issue, the version of paho-mqtt installed on PythonAnywhere might be outdated. Older versions can have bugs with TLS handling or auth parsing that are fixed in newer releases.
Fix: Upgrade paho-mqtt on PythonAnywhere to the latest version compatible with Python 2.7:
pip install --upgrade paho-mqtt
Verification Steps
- First, test the code with port 8883 and correct auth format—this resolves the majority of PythonAnywhere MQTT issues.
- If you still hit errors, check the paho-mqtt version in both environments (
pip show paho-mqtt) and ensure they match or are up-to-date. - Double-check that your token is valid (copy-paste it directly to avoid typos).
内容的提问来源于stack exchange,提问作者FoxSam12

