Mosquitto mqtt broker linux

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

CheatSheet (Шпаргалка): Установка и базовая настройка MQTT брокера Eclipse Mosquitto на Ubuntu | Debian | Kali Linux

huny-huny/CheatSheet-MQTT-Eclipse-Mosquitto

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Установка и базовая настройка MQTT брокера Eclipse Mosquitto на Ubuntu | Debian | Kali Linux

Eclipse Mosquitto — это брокер сообщений с открытым исходным кодом, который реализует протокол MQTT. Mosquitto легок и подходит для использования на всех устройствах, от одноплатных компьютеров с низким энергопотреблением до полноценных серверов. Варианты установки на разные операционные системы кратко описаны на официальном сайте: https://mosquitto.org/download/

Ниже представлена моя «Шпаргалка» (CheatSheet) 😉

Для выполнения некоторых команд в терминале могут понадобятся права администратора. Для этого просто наберите перед командой sudo:

Для обновления вашей системы (обновление пакетов), выполните:

apt-get update && apt-get upgrade -y

Устанавливаем MQTT брокера и клиента Mosquitto:

apt install mosquitto mosquitto-clients -y

Настроим для Mosquitto подписку по логину и паролю (пример для логина «huny»).

Читайте также:  Check ssl certificate linux

mosquitto_passwd -c /etc/mosquitto/passwd huny

Далее, по запросу, нужно будет ввести два раза ваш пароль для Mosquitto.

Связка логин-пароль будет храниться по следующему пути — /etc/mosquitto/passwd

Откроем файл, что бы убедиться, что пароль создан:

Закроем файл, нажав CTRL + X

Запретим анонимные подключения к Mosquitto. Открываем файл default.conf:

Файл должен быть пустой, вставляем туда этот текст:

Сохраняем и закрываем файл, нажав CTRL + X, Y, а затем ENTER.

Перезагружаем Mosquitto чтобы применить изменения:

systemctl restart mosquitto

На этом этапе MQTT брокер Mosquitto у нас успешно запущен и защищён паролем.

UPD1: Добавление / удаление пользователей в MQTT брокер (Mosquitto)

Для примера добавим пользователя с логином huny2 и паролем parol2:

mosquitto_passwd -b /etc/mosquitto/passwd huny2 parol2

Проверяем что добавился, открыв файл паролей.

Закрываем файл, нажав CTRL + X

Перезагружаем Mosquitto чтобы применить изменения:

systemctl restart mosquitto

Удалить пользователя huny2:

mosquitto_passwd -D /etc/mosquitto/passwd huny2

Проверяем, что действвительно удалён, открыв файл паролей:

Закрываем файл, нажав CTRL + X

Перезагружаем Mosquitto чтобы применить изменения:

systemctl restart mosquitto

UPD2: Изменим порт MQTT брокера Mosquitto c 1883 на 8883 (пример), а 1883 привяжем к localhost (недоступен извне).

Открываем файл default.conf:

Сохраняем и закрываем файл, нажав CTRL + X, Y, а затем ENTER.

Перезагружаем Mosquitto чтобы применить изменения:

systemctl restart mosquitto

UPD3: Управление состоянием Mosquitto:

Посмотреть текущий статус:

systemctl status mosquitto

systemctl status mosquitto.service

Изменение статуса текущего сеанса:

systemctl start mosquitto

systemctl start mosquitto.service

systemctl stop mosquitto.service

Для изменения состояния при запуске (не влияет на текущее состояние):

systemctl enable mosquitto

systemctl disable mosquitto

systemctl enable mosquitto.service

systemctl disable mosquitto.service

About

CheatSheet (Шпаргалка): Установка и базовая настройка MQTT брокера Eclipse Mosquitto на Ubuntu | Debian | Kali Linux

Источник

Download

The binary packages listed below are supported by the Mosquitto project. In many cases Mosquitto is also available directly from official Linux/BSD distributions.

Windows

  • mosquitto-2.0.15-install-windows-x64.exe (64-bit build, Windows Vista and up, built with Visual Studio Community 2019)
  • mosquitto-2.0.15-install-windows-x32.exe (32-bit build, Windows Vista and up, built with Visual Studio Community 2019)

See also README-windows.md after installing.

Mac

Mosquitto can be installed from the homebrew project. See brew.sh and then use brew install mosquitto

Linux distributions with snap support

Debian

  • Mosquitto is now in Debian proper. There will be a short delay between a new release and it appearing in Debian as part of the normal Debian procedures.
  • There are also Debian repositories provided by the mosquitto project, as described at https://mosquitto.org/2013/01/mosquitto-debian-repository

Raspberry Pi

Mosquitto is available through the main repository.

Читайте также:  Linux остановить запустить процесс

There are also Debian repositories provided by the mosquitto project, as described at https://mosquitto.org/2013/01/mosquitto-debian-repository/

Ubuntu

Mosquitto is available in the Ubuntu repositories so you can install as with any other package. If you are on an earlier version of Ubuntu or want a more recent version of mosquitto, add the mosquitto-dev PPA to your repositories list — see the link for details. mosquitto can then be installed from your package manager.

Mosquitto Enhancements

These projects can be used to add extra features to Mosquitto.

  • Management Center: A web UI for managing Mosquitto instances. In particular, this offers a convenient UI for managing clients, groups and roles as in the new Dynamic Security plugin.
  • mosquitto-go-auth: A flexible authentication and authorisation plugin, with many different backends and features.
  • Mosquitto-PHP: A PHP wrapper for the libmosquitto client library, to allow creating MQTT clients in PHP.

Источник

Install Mosquitto MQTT Broker On Ubuntu 20.04 Server

Mosquitto is an open-source message broker that uses the Message Queuing Telemetry Transport (MQTT) Protocol. MQTT runs on top of the TCP/IP model and is the standard messaging platform for the Internet of Things (IoT).

Since the MQQT protocol is extremely lightweight, its small code footprint allows you to create applications for devices with minimal resources such as short battery life, limited network bandwidth, and unreliable internet connections.

The Mosquitto application supports the publisher/subscriber topology. In this model, clients connect to the Mosquitto server, which acts as a broker to distribute information to other clients subscribed or sending messages to a channel.

In this guide, you’ll install and configure the Mosquitto application and learn how the event-driven MQQT protocol works with IoT applications.

Prerequisites

To follow along with this guide, you need:

1. Install the Mosquitto Server

You’ll pull the mosquitto package from Ubuntu’s software repository by executing the following steps.

    SSH to your server and update the package information index.

$ sudo apt install -y mosquitto 
$ sudo systemctl status mosquitto 
● mosquitto.service - Mosquitto MQTT v3.1/v3.1.1 Broker Loaded: loaded (/lib/systemd/system/mosquitto.service; enabled; vendor pr> Active: active (running) since Fri 2021-10-08 06:29:25 UTC; 12s ago Docs: man:mosquitto.conf(5) man:mosquitto(8) . 
$ sudo systemctl stop mosquitto 
$ sudo systemctl start mosquitto 
$ sudo systemctl restart mosquitto 

2. Install and Test the Mosquitto Clients

When using an MQTT client, you connect to the Mosquitto broker to send and receive messages on different topics depending on the application’s use case. A client can either be a publisher, a subscriber, or both.

Читайте также:  Install pip oracle linux

    The Mosquitto package ships with a command-line client that allows you to test the server functionalities. Install the client.

$ sudo apt install -y mosquitto-clients 
  • home/lights/sitting_room
  • home/lights/kitchen
  • home/lights/master_bedroom
  • home/lights/kids_bedroom
$ mosquitto_sub -t "home/lights/sitting_room" 
$ mosquitto_pub -m "ON" -t "home/lights/sitting_room" 
$ mosquitto_pub -m "OFF" -t "home/lights/sitting_room" 
  • Monitoring patients’ heartbeats and sending them to a central server for monitoring by doctors. This avoids heavy transport costs that the patients could incur by traveling to the hospital.
  • In the gas and the oil industry, MQQT devices monitor different parameters and send the data to a central broker. Usually, this involves thousands of sensors in remote locations that collect and send data through satellite links that are billed per data usage. Luckily, the MQQT topology keeps the transmission minimal and only pushes data to the server when necessary.
  • In the transport industry, MQQT devices monitor the location of trains in real-time and send data to the companies’ headquarters in order to provide better insights to customers who want to travel without any delays.
  • Also, the Mosquitto broker can be used as a middle layer in a chat application to refresh the online status of users and pass messages between end-users.
  • Another common scenario where the Mosquitto server can be a good fit is in decoupled systems. Clients can send data to the broker, which then sends the data to a database for permanent storage.

3. Secure the Mosquitto Server

By default, the Mosquitto server is not secured. However, you can make some configuration settings to secure it with usernames and passwords.

    Mosquitto reads configuration information from the following location.

$ sudo nano /etc/mosquitto/conf.d/default.conf 
allow_anonymous false password_file /etc/mosquitto/passwd 
$ sudo nano /etc/mosquitto/passwd 
john_doe:EXAMPLE_PASSWORD mary_smith:EXAMPLE_PASSWORD_2 
$ sudo mosquitto_passwd -U /etc/mosquitto/passwd 
$ sudo cat /etc/mosquitto/passwd 
john_doe:$6$TSzNycsj. 5Qyvgd4g== mary_smith:$6$DtlKf1lG. /rLHIL0Q== 
$ sudo systemctl restart mosquitto 
$ mosquitto_sub -u john_doe -P EXAMPLE_PASSWORD -t "home/lights/sitting_room" $ mosquitto_pub -u john_doe -P EXAMPLE_PASSWORD -t "home/lights/sitting_room" -m "ON" 
$ mosquitto_pub -m "ON" -t "home/lights/sitting_room" $ mosquitto_sub -t "home/lights/sitting_room" $ mosquitto_sub -u john_doe -P WRONG_PASSWORD -t "home/lights/sitting_room" $ mosquitto_pub -u john_doe -P WRONG_PASSWORD -t "home/lights/sitting_room" -m "ON" 
. Connection error: Connection Refused: not authorised. 

Conclusion

In this tutorial, you’ve installed and configured the Mosquitto server on your Ubuntu 20.04 server. You’ve also used the command-line interface to subscribe and publish messages to a sample topic. Consider using the Mosquitto server next time when deploying an IoT application.

Want to contribute?

You could earn up to $600 by adding new articles.

Источник

Оцените статью
Adblock
detector