네트워크/MQTT

[MQTT] 1. Mosquitto 셋업

IT 기술자 2025. 1. 17. 11:00

Step 1. mosquitto 설치

1. 설치

sudo apt update
sudo apt install mosquitto mosquitto-clients

2. 설치 확인

mosquitto -v

3. 테스트

3.1 구독

mosquitto_sub -h localhost -t test/topic

3.2 발행

mosquitto_pub -h localhost -t test/topic -m 'hello mqtt'

 

Step 2. TLS 세팅

1. 인증키 생성과 mosquitto 폴더에 복사

openssl genrsa -des3 -out ca.key 2048
openssl req -new -x509 -days 1826 -key ca.key -out ca.crt
Country Name : KR
State or Province Name : seoul
Locality Name :
Organization Name : korea_company
Organizational Unit Name : lab
Common Name : hostname 입력
Email Address : email 입력
openssl genrsa -out server.key 2048
openssl req -new -out server.csr -key server.key
Country Name : KR
State or Province Name : seoul
Locality Name :
Organization Name : korea_company
Organizational Unit Name : lab
Common Name : ip/domain 입력
Email Address : email 입력

 

예) ip/domain : 192.168.1.100

 

openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt
chmod +r server.key
sudo cp ca.crt /etc/mosquitto/ca_certificates/
sudo cp server.crt server.key /etc/mosquitto/certs/

 

2. mosquitto 설정

sudo vi /etc/mosquitto/mosquitto.conf
listener 8883
allow_anonymous true
require_certificate true
cafile /etc/mosquitto/ca_certificates/ca.crt
keyfile /etc/mosquitto/certs/server.key
certfile /etc/mosquitto/certs/server.crt
tls_version tlsv1.2

 

서비스 재시작

sudo service mosquitto restart

 

3. 테스트

3.1 구독

mosquitto_sub -h [ip/domain] -p 8883 --cafile /etc/mosquitto/ca_certificates/ca.crt --cert /etc/mosquitto/certs/server.crt --key /etc/mosquitto/certs/server.key -t [topic]

 

3.2 발행

mosquitto_pub -h [ip/domain] -p 8883 --cafile /etc/mosquitto/ca_certificates/ca.crt --cert /etc/mosquitto/certs/server.crt --key /etc/mosquitto/certs/server.key -t [topic] -m 'hello tls'
예) ip/domain : 192.168.1.100, topic : test/topic