ubuntu18.04系统mqtt+tls服务器搭建——mosquitto配置

前言

设备端调试mqtt+ssl的功能,由于没有现成的服务器可以接入,考虑使用本地ubuntu安装mosquitto服务,加快调试进度

如有异议,请指正

安装mosquitto
引入mosquitto仓库
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
更新软件包
sudo apt-get update
安装mosquitto
sudo apt-get install mosquitto-clients -y
证书生成
openssl生成证书
  • 查看openssl版本,未安装的可以通过以下命令安装
sudo apt-get install openssl
sudo apt-get install libssl-dev
openssl version

在这里插入图片描述

制作CA证书与密钥

  • 生成key
openssl genrsa -des3 -out ca.key 2048
  • 生成ca的crt文件
openssl req -new -x509 -days 1826 -key ca.key -out ca.crt

制作server证书与密钥,需要用到之前的CA证书

  • 生成私钥
openssl genrsa -out server.key 2048
  • 证书请求文件
openssl req -new -out server.csr -key server.key
  • 签署证书
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 360

同上,制作client证书与密钥,使能双向认证时会用到

openssl genrsa -out client.key 2048
openssl req -new -out client.csr -key client.key
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 360

验签证书,打印OK代码验证成功

openssl verify -CAfile ca.crt server.crt
mosquitto配置

修改mosquitto.conf

sudo vim /etc/mosquitto/mosquitto.conf
  • 增加证书路径与配置信息
# 日志文件
log_dest file /var/log/mosquitto/mosquitto.log
# 禁止匿名访问
allow_anonymous false
# 认证配置
password_file /etc/mosquitto/pwfile
#权限配置
acl_file /etc/mosquitto/aclfile

# 开启双向认证
#require_certificate true
# 端口
listener 8883
# CA证书路径
cafile /home/ca.crt
# server证书路径
certfile /home/server.crt
# server私钥路径
keyfile /home/server.key
创建文件
sudo touch /etc/mosquitto/pwfile
创建用户与密码,用户名分别为device1、device2,需要输入两次密码;客户端连接时需要输入用户信息

-c 覆盖第一次创建的用户

sudo mosquitto_passwd -c  /etc/mosquitto/pwfile device1
sudo mosquitto_passwd /etc/mosquitto/pwfile device2
修改aclfile,配置主题
sudo vim /etc/mosquitto/aclfile
# device1只能发布以tp_test1为前缀的主体,订阅以tp_test2开头的主题
user device1
topic write tp_test1
topic read  tp_test2
# device2只能发布以tp_test2为前缀的主体,订阅以tp_test1开头的主题
user device2
topic write tp_test2
topic read  tp_test1
  • 启动mosquitto服务
mosquitto -c /etc/mosquitto/mosquitto.conf -d
  • 查看状态
service mosquitto status
通信测试
  • 安装客户端client
sudo apt-get install mosquitto-clients
订阅消息
  • device2订阅tp_test1主题
mosquitto_sub -h localhost -p 8883 -t "tp_test1" -u device2 -P 123456 -i "device2" --cafile /home/ca.crt --cert /home/client.crt --key  /home/client.key --insecure 
发布消息
  • device1 发布消息
mosquitto_pub -h localhost -p 8883 -t "tp_test1" -u device1 -P 123456 -i "device1" -m "device1 pub message"  --cafile /home/ca.crt --cert /home/client.crt --key /home/client.key --insecure

在这里插入图片描述

PS

windows系统可以使用mqtt.fx客户端来进行服务验证,下载地址,后续便可使用真实的设备进行通信调试
在这里插入图片描述

mosquitto_pub命令参数
参数描述
-h服务器主机,本地使用localhost
-t指定主题
-u用户名
-P密码
-i客户端唯一id
-m发布消息的内容
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值