个人智能家居系统 - MQTT服务器搭建(centOS7.3)

0x00 参考

  • 在CentOS7 上安装mosquitto1.4.1服务器,实现MQTT信息推送功能并增加websocket功能
  • mosquitto的鉴权配置

0x01 配置

  • General configuration
    所见即所得,保持默认即可
  • Default listener
    1. # 设置端口
    2. port 1883
    3. # 设置最大连接数
    4. max_connections -1
    5. # 使用协议,mqtt或者websocket
    6. protocol mqtt
  • SSL/TLS support
    用于 default listerner 的安全设置,暂未设置
  • Extra listeners
    用于 websocket ,暂未设置
  • SSL/TLS support
    用于 Extra listeners 的安全设置,暂未设置
  • Persistence
    持续性设置,即 mosquitto 重启后恢复设置,暂未设置
    而且客户端的断线重连机制更加稳妥
  • Logging
    开启服务时重定向 stdout 等信息至文件,这里只设置 type
  • Security
    1. # 设置前缀
    2. clientid_prefixes guduyl
    3. # 禁止匿名登录
    4. allow_anonymous false
    5. # 设置用户名密码文件
    6. password_file /etc/mosquitto/pwfile
    7. # 设置权限信息文件
    8. acl_file /etc/mosquitto/aclfile
  • Bridges
    用于分布式服务器,暂未设置
  • SSL/TLS support
    分布式服务器安全设置,暂未设置
  • External config files
  • rsmb options

用户名密码设置

  • mosquitto_passwd 命令,查看帮助即可

权限文件设置

  • 仿照 aclfile.example 文件
    • test/jh/# 可匹配 test/jh/a/b/c, test/jh/a/b, test/jh/a.test/jh
    • test/jh/+ 可匹配 test/jh/a, test/jh/b, 但是不能匹配 test/jh/a/b

启动停止

  • 启动 ```shell

    ! /bin/bash

ps -ef | grep mosquitto | tee /tmp/graduation.tmp

lines=$(awk ‘END{print NR}’ /tmp/graduation.tmp) lines=expr $lines + 1 for ((i=1; i<$lines; ++i)) do uid=$(sed -n “$i, 1p” /tmp/graduation.tmp | awk ‘{print $1}’) if [ $uid == “mosquit+” ] ; then break fi done

if [ $i != $lines ] ; then echo “the mosquitto1.4.1 had been started already” else echo “Starting the mosquitto1.4.1 …” mosquitto -d -c /etc/mosquitto/mosquitto.conf > /root/graduation/mosquitto.log 2>&1 echo “the mosquitto1.4.1 has been started” echo “the log file is /root/graduation/mosquitto.log” fi

rm -f /tmp/graduation.tmp

  1. - 停止
  2. ```shell
  3. #! /bin/bash
  4. ps -ef | grep mosquitto | tee /tmp/graduation.tmp
  5. lines=$(awk 'END{print NR}' /tmp/graduation.tmp)
  6. lines=`expr $lines + 1`
  7. for ((i=1; i<$lines; ++i))
  8. do
  9. uid=$(sed -n "$i, 1p" /tmp/graduation.tmp | awk '{print $1}')
  10. if [ $uid == "mosquit+" ] ; then
  11. break
  12. fi
  13. done
  14. if [ $i != $lines ] ; then
  15. pid=$(sed -n "$i, 1p" /tmp/graduation.tmp | awk '{print $2}')
  16. echo "killing $pid ..."
  17. kill $pid
  18. echo "the mosquitto1.4.1 has been stopped"
  19. else
  20. echo "the mosquitto1.4.1 has not been started yet"
  21. fi
  22. rm -f /tmp/graduation.tmp
  • 重启 ```shell

    ! /bin/bash

/root/graduation/stop.sh /root/graduation/start.sh ```