咸鱼

咸鱼是以盐腌渍后,晒干的鱼

0%

Mosquitto从零部署

环境

全新的Ubuntu 16.04,所需编译环境:

1
$ sudo apt-get install build-essential openssl libssl-dev libc-ares-dev uuid-dev cmake -y

安装libwebsockets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

$ wget https://warmcat.com/git/libwebsockets/snapshot/libwebsockets-3.0.0.tar.gz

$ tar -zxvf libwebsockets-3.0.0.tar.gz

$ cd libwebsockets-3.0.0

$ mkdir build

$ cd build

$ cmake ..

$ make

$ sudo make install

# 使库文件软链接立刻生效
$ sudo ldconfig

安装mosquttio

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

$ wget https://mosquitto.org/files/source/mosquitto-1.5.tar.gz

$ tar -zxvf mosquitto-1.5.tar.gz

$ cd mosquitto-1.5/

$ vim mosquitto.conf

port 1883
protocol mqtt

listener 9001
protocol websockets

$ vim config.mk
WITH_WEBSOCKETS:=yes

$ make

$ sudo make install

# 使库文件软链接立刻生效
$ sudo ldconfig

启动

1
2
3
4
5
6
7
$ sudo mosquitto -c /etc/mosquitto/mosquitto.conf.example
1527152208: mosquitto version 1.5 starting
1527152208: Config loaded from /etc/mosquitto/mosquitto.conf.
1527152208: Opening websockets listen socket on port 9001.
1527152208: Opening ipv4 listen socket on port 1883.
1527152208: Opening ipv6 listen socket on port 1883.
$ sudo mosquitto -c /etc/mosquitto/mosquitto.conf.example -d (守护进程)

用户

1
2
3
4
5
6
7
8
9
10
$ sudo vim /etc/mosquitto/mosquitto.conf
allow_anonymous false
password_file /etc/mosquitto/pwfile.conf

# -c 表示覆盖创建用户, pwfile会被清空
$ sudo mosquitto_passwd -c /etc/mosquitto/pwfile.conf admin
#输入两次密码

$ sudo mosquitto_passwd /etc/mosquitto/pwfile.conf test

更多配置参考

授权插件

如上手动添加用户在生产环境不太现实,接下来将通过HTTP插件实现用户授权管理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
$ git clone https://github.com/jpmens/mosquitto-auth-plug.git
$ cd mosquitto-auth-plug
$ cp config.mk.in config.mk
$ vim config.mk

# 打开HTTP授权的方式
BACKEND_HTTP ?= yes
# mosquitto 源码的路径
MOSQUITTO_SRC = /home/root/mosquitto-1.5

$ make

# 如果报错 fatal error: curl/curl.h: No such file or directory
# 安装libcurl4-openssl-dev
$ sudo apt-get install libcurl4-openssl-dev

# 将编译好的so文件和 mosquitto 放在一起
$ cp auth-plug.so /usr/local/sbin/

$ vim /etc/mosquitto/mosquitto.conf
#password_file /etc/mosquitto/pwfile.conf
auth_plugin /usr/local/sbin/auth-plug.so

auth_opt_backends http
auth_opt_http_ip 192.168.5.33
auth_opt_http_port 8089
auth_opt_http_getuser_uri /auth
auth_opt_http_superuser_uri /superuser
auth_opt_http_aclcheck_uri /acl

# 重启 mosquitto

安装完成插件之后,只要编写授权的 HTTP服务,响应插件发起的授权请求,通过响应码返回结果就OK了。
除了HTTP,还可以通过MySQL/Redis等数据库来实现。