Debian9下Mosquitto ACL配置异常及客户端ID问题求助
针对你遇到的两个问题,结合你使用的Debian 9和Mosquitto 1.4.10版本,我来逐一分析解决:
问题1:匿名用户可执行发布命令但订阅收不到消息
原因分析
你当前的配置里只添加了acl_file和password_file,但没有禁用匿名访问(allow_anonymous false)。Mosquitto默认允许匿名用户连接,不过你的ACL规则已经限制了匿名用户仅能订阅myTopic/#,不能发布。所以你执行匿名发布时,命令本身不会报错(因为连接成功了),但Broker会通过ACL拦截这条消息,导致订阅端收不到。
解决步骤
- 编辑Mosquitto配置文件:
nano /etc/mosquitto/mosquitto.conf - 添加或修改以下配置,禁用匿名访问(确保只有认证用户能连接):
如果你想保留匿名用户但严格限制其只能订阅,也可以不修改这条,但需要确保ACL规则生效,此时匿名发布的消息会被拦截,你可以在日志里看到对应的拒绝记录。allow_anonymous false - 重启Mosquitto服务使配置生效:
service mosquitto restart - 测试验证:
- 匿名发布应该直接被拒绝:
此时会收到“Connection Refused: not authorised.”的错误。mosquitto_pub -d -t myTopic/test -m "test" - 使用认证用户发布,订阅端能正常接收:
# 发布端 mosquitto_pub -d -u myUsername -P 你的密码 -t myTopic/test -m "Hello Auth" # 订阅端(如果是认证用户也要加-u和-P) mosquitto_sub -d -u myUsername -P 你的密码 -t myTopic/test
- 匿名发布应该直接被拒绝:
问题2:日志提示“ACL denying access to client with dangerous client id”
原因分析
这个问题是Mosquitto 1.4.x版本的已知bug,当你的ACL配置里包含pattern规则(比如你用的pattern write $SYS/broker/connection/%c/state),Broker会将包含斜杠/的默认client id(比如mosqpub/7977-Debian-93-)判定为“危险”,因为早期版本对client id的模式匹配存在逻辑缺陷,这个问题在Mosquitto 1.5及以上版本才被修复。
解决步骤
由于你使用的Debian 9默认提供的是Mosquitto 1.4.10,升级到高版本可能需要添加第三方源,这里提供两种解决方法:
- 临时快速解决:发布或订阅时手动指定不含斜杠的client id,避免使用默认的
mosqpub/xxx格式:# 发布时指定client id mosquitto_pub -d -i MyPubClient -u myUsername -P 你的密码 -t myTopic/test -m "test" # 订阅时指定client id mosquitto_sub -d -i MySubClient -u myUsername -P 你的密码 -t myTopic/test - 永久修复(升级版本):通过添加Mosquitto官方源升级到1.5+版本:
升级完成后重启服务,默认client id的问题就会被修复。# 添加官方源密钥 wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key apt-key add mosquitto-repo.gpg.key # 添加源 cd /etc/apt/sources.list.d/ wget http://repo.mosquitto.org/debian/mosquitto-stretch.list # 更新并升级 apt-get update apt-get upgrade mosquitto
额外验证建议
你可以查看Mosquitto日志确认配置是否正确加载:
cat /var/log/mosquitto/mosquitto.log
正常情况下,重启后应该能看到类似以下的日志:
Loading config file /etc/mosquitto/mosquitto.conf
Loading password file /etc/mosquitto/passwd
Loading ACL file /etc/mosquitto/aclfile
内容的提问来源于stack exchange,提问作者Nisbo

