Mosquitto是一款实现MQTT(消息队列遥测传输)协议的开源消息代理。MQTT是一种轻量级的TCP/IP消息平台,专为资源受限的物联网设备设计,例如低带宽或电池寿命有限的设备。它采用发布-订阅(pub/sub)拓扑结构,发布者将消息发送到代理,订阅者通过通道接收消息。本指南将在Ubuntu 24.04上安装Mosquitto,将其作为systemd服务进行管理,使用Mosquitto命令行客户端测试发布/订阅消息,并通过密码认证保护代理。完成后,您将拥有一个受密码保护的Mosquitto MQTT代理,可用于物联网消息传递。
前提条件:一台Ubuntu 24.04服务器,一个具有sudo权限的非root用户,以及已更新的系统。
![]()
Mosquitto在Ubuntu 24.04的默认软件源中可用。
安装Mosquitto
1. 安装Mosquitto软件包:
$ sudo apt install -y mosquitto2. 验证已安装的版本:
$ mosquitto -v输出示例:
1730087147: mosquitto version 2.0.18 starting1730087147: Using default config.1730087147: Starting in local only mode. Connections will only be possible from clients running on this machine.1730087147: Create a configuration file which defines a listener to allow remote access.管理Mosquitto系统服务
Mosquitto作为系统服务运行,服务名为mosquitto。
1. 查看服务状态:
$ sudo systemctl status mosquitto输出示例:
● mosquitto.service - Mosquitto MQTT Broker Loaded: loaded (/usr/lib/systemd/system/mosquitto.service; enabled; preset: enabled> Active: active (running) since Fri 2024-10-25 06:51:37 UTC; 12min ago Docs: man:mosquitto.conf(5) man:mosquitto(8)...测试发布与订阅
安装客户端工具包:
$ sudo apt install -y mosquitto-clients在一个终端中订阅主题:
$ mosquitto_sub -t "home/sensor/temperature" &在另一个终端中向同一主题发布消息,订阅端即可收到消息,验证发布-订阅机制正常工作。
添加密码保护
默认配置下Mosquitto允许匿名连接。要启用密码认证,需修改配置文件/etc/mosquitto/mosquitto.conf,添加监听端口和密码文件路径,并使用mosquitto_passwd命令创建用户。配置完成后重启服务,代理将要求客户端提供用户名和密码才能连接。
至此,一个带密码保护的Mosquitto MQTT代理部署完成。整个过程无需编译源码,Ubuntu 24.04的软件源已处理了大部分安装细节。
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.