MQTT服务器搭建——Liunx安装mosquitto,并设置用户密码

2023-03-14,,

一、安装

1、下载mosquitto安装包

地址:http://mosquitto.org/files/source/

2、安装依赖包

yum install gcc gcc-c++ libstdc++-devel 

yum install openssl-devel -y

yum install c-ares-devel -y

yum install uuid-devel -y

yum install libuuid-devel -y

yum install c-ares-devel

3、编译并安装

解压下载的安装包:tar zxvf mosquitto-2.0.10.tar.gz

进入解压后的文件夹:cd mosquitto-2.0.10

执行命令:make && make install

4、安装后进入 /etc/mosquitto中,复制配置文件

cp mosquitto.conf.example mosquitto.conf

5、启动

mosquitto -c /etc/mosquitto/mosquitto.conf

//后台启动
mosquitto -c /etc/mosquitto/mosquitto.conf -d

6、关闭,kill进程

ps -aux | grep mosquitto
kill -9 2438

至此安装mosquitto完毕!

二、设置用户密码

1、打开配置文件为/etc/mosquitto/mosquitto.conf

配置如下 :

listener 1883  //配置允许外部访问的端口设置
allow_anonymous false //配置不允许匿名访问,需输入账号密码才可订阅或者发布
password_file /etc/mosquitto/pwfile.example //配置账号密码存放的路径

2、设置用户密码

命令如下:

mosquitto_passwd /etc/mosquitto/pwfile.example 用户名

回车后,按照提示输入两次密码即可!

3、用户测试验证

启动 mosquitto:

mosquitto -c /etc/mosquitto/mosquitto.conf

(订阅端)客户端启动:

mosquitto_sub -h 地址 -t 主题 -u 用户名 -P 密码

(发布者)客户端启动:

mosquitto_pub -h 地址 -t 主题 -u 用户名 -P 密码 -m 发布内容

三、补充问题

编译问题

1、fatal error: cjson/cJSON.h: No such file or directory

解决:需要安装cJSON(这里cJSON的安装,yum和apt不一定能找到,可以直接从github上下载源码压缩包,然后解压,进入目录,并make,make install)

启动订阅客户端问题

1、error while loading shared libraries: libmosquitto.so.1: cannot open shared object file: No such file or directory

解决:执行以下命令:

sudo ln -s /usr/local/lib/libmosquitto.so.1 /usr/lib/libmosquitto.so.1
ldconfig

2、error while loading shared libraries: libcjson.so.1: cannot open shared object file: No such file or directory

解决:

方法1:

编辑/etc/ld.so.conf文件,在新的一行中加入库文件所在目录(/usr/local/lib);

运行ldconfig,以更新/etc/ld.so.cache文件;

方法2:

在/etc/ld.so.conf.d/目录下新建任何以.conf为后缀的文件(touch mqtt.conf),在该文件中加入库文件所在的目录;

运行ldconfig,以更新/etc/ld.so.cache文件;

3、Warning: Unable to drop privileges to 'mosquitto' because this user does not exist. Trying 'nobody' instead.

解决:

在allow_anonymous 前面加一个 user root

user root
allow_anonymous false

或者创建mosquitto用户和组

groupadd mosquitto
useradd -g mosquitto mosquitto
chown -R mosquitto:mosquitto /etc/mosquitto/

四、参考以下文章

https://www.cnblogs.com/chen1-kerr/p/7258487.html

https://www.cnblogs.com/IC1101/p/14749722.html

https://blog.csdn.net/u012377333/article/details/69397124

https://www.cnblogs.com/x_wukong/p/4722903.html

https://blog.csdn.net/houjixin/article/details/46711547

MQTT服务器搭建——Liunx安装mosquitto,并设置用户密码的相关教程结束。

《MQTT服务器搭建——Liunx安装mosquitto,并设置用户密码.doc》

下载本文的Word格式文档,以方便收藏与打印。