Using The Mosquitto_pub and Mosquitto_sub MQTT Client Tools- Examples

The Mosquitto_pub and Mosquitto_sub client utilities comes with the Mosquitto package, and are excellent tools for conducting quick tests and troubleshooting..

In this tutorial we are going to be looking at some examples of using these tools for publishing and subscribing.

Publishing Using The Mosquitto_pub Client

The screen shot shot below shows a simple publish, and a publish with the debug flag (-d) set.


In the first example the message is published and the client exits without displaying any messages.

If you enable the debugging using the -d flag then you can see the connect,publish and disconnect messages.

Notice the -h flag sets the host name or IP address. To get help use the –help flag.

e.g. mosquitto_pub –help

Useful Flag Options and Examples

-r  Sets retain flag
-n  Sends Null message useful for clearing retain message.
-p – Set Port number Default is 1883
-u – Provide a username
-P – Provide a password
-i – Provide client name
-I – Provide a client id prefix- Used when testing client restrictions using prefix security.

Publish With Username and Password

Uses -u username and -P password flags


Publish with Retain Flag

Uses -r Flag


Clear Retained Message

Uses the -r -n flag combination


Publish with Client Name

This  option is useful when testing client restrictions using prefixes or client names with ACLs.

Uses -i option. You could also use the -I option if you just needed prefixes.


Publishing JSON Data

JSON Data has a special format described here. When is comes to publishing with the mosquitto_pub client you need to escape the quotes so that they are included.

So don’t use {“status”:”off”} but instead use: {\”status\”:\”off\”}.

If you are sending multiple values then you need to put the entire string in quotes:

mosquitto_pub -h localhost -t test -m "{\"value1\":20,\"value2\":40}"

On Linux you can also use shell variables. If you have a shell variable called var1 then:

mosquitto_pub -h localhost -t test -m "{\"value1\":20,\"value2\":$var1}"

Mosquitto_pub -Publish Using SSL

Note: you will need to copy the CA.crt file into the appropriate directory. Use the –insecure switch if the name on the certificate doesn’t match the actual broker name.


There is also a option to publish a will message using the –will-topic flag but I couldn’t get this to work.

Using The Mosquitto_sub Client

This is useful for quickly monitoring a topic. Flag options are mostly the same as the mosquitto_pub client.

When you start this client it runs indefinitely until stopped using CTRL+C.


A useful option is the -C flag which will disconnect after receiving a certain number of messages.


Using the -v  (verbose option will show the topic name as well as the message.


The debug option -d flag is useful when you want to see the messages flags like qos and retain flag.


You can change the QOS when subscribing using the -q switch.



  • I didn’t get the scripts to work on Windows XP -Error not a valid win32 application
  • On Windows 7 and 10 they gave an error regarding a missing msvcr100.dll file. I found the file on my system and copied it to the Mosquitto directory and they worked OK.


Here is the pub manual page, and here is the sub manual page.

Video- Using the mosquitto_pub and mosquitto_sub client tools


The mosquitto_pub and mosquitto_sub client utilities are excellent tools for testing and troubleshooting MQTT and broker problems.

Other Related Articles and Resources:

Please rate? And use Comments to let me know more
[Total: 15   Average: 4.6/5]


  1. Is it possible to resend topics received by the mosquitto broker running on a raspberry pi to resend in different format?

    For Domoticz topics: domoticz/out to domoticz/out/idx where idx ithe number from the body or message from the original topic

  2. Hi Steve,
    I have a groov Epic running Node-Red but I cannot get it to connect to my MQTT broker. I downloaded Eclipse MQTT v5/3.1.1 and installed it on my PC. I started the service. I tested it by opening a second window and doing the mosquitto_sub and mosquitto_pub routines. I created rules to allow port 1883 to receive and send through the firewall. Because it wouldn’t connect I installed wireshark on the broker PC and I can see the groov attempting to talk to the MQTT pc. Next I installed MQTT on another PC and attempted to send a message using the addition of -h When I attempt to get the new PC to pub to the topic I have a sub running for on the MQTT I get the error “No connection could be made because the target machine actively refused it”. Wireshark also shows the attempt on port 1883 of the broker for this device. What am I missing?

    1. The message you are getting is usually caused by the broker not active on that port or that port is being blocked.

  3. Hi Steve,

    Thank you for this tutorial about Mosquitto_pub and Mosquitto_sub MQTT.

    I am trying to implement MQTT in C programming. Need to publish some values from sensor.

    Do you have any tutorials or guide on how to implement MQTT in C programming ?

  4. Hi Steve,

    mosquitto_sub doesn’t seem to work. It doesn’t show any message and keeps running till I press ctrl+c, doesn’t matter if a use the flag -C or not.

    I used the the second example (with debug flag) for publishing and it gave me the same details as the ones in image.

    C:\Program Files\mosquitto>mosquitto_pub -h {my-ip} -m “test message” -t house/bulb1 -d
    Client mosq-uzMlvnQQY5zT68jJ67 sending CONNECT
    Client mosq-uzMlvnQQY5zT68jJ67 received CONNACK (0)
    Client mosq-uzMlvnQQY5zT68jJ67 sending PUBLISH (d0, q0, r0, m1, ‘house/bulb1’, … (12 bytes))
    Client mosq-uzMlvnQQY5zT68jJ67 sending DISCONNECT

      1. mosquitto_sub -h {my-ip} -t house/#

        One update though. It seems to show the retained messages (only once) but not the other ones.

        1. That should work ok just use -d at the end. If it doesn’t can you send me a screenshot of the pub and sub. Do you have access to the broker console to see if it is sending the messages.

          1. It’s working, thanks for the help!
            I was a bit confused and was writing both the _pub and _sub commands in the same console, so of course the not retained messages were not showing. Once I set _pub and _sub consoles separately, I could see the published messages.

  5. hi,
    while publishing i got error
    connection error: connection Refused: not authorised
    client test sending DISCONNECT

    command–mosquitto_pub -h localhost -u uname -p passcode -m “test” -t drove/tmt -p 1884st -p 1884 -r -d

  6. Hi
    I am trying to repeat the published message using the following command
    mosquitto_pub -h -u “test” -P “test” -m “hi” –repeat 10
    It gives me error : “–repeat” unknown command
    How can I repeat my publish message?


  7. Hi Steve, Thank you very much for your tutorial. I’ve been trying to find ways to connect my edge devices(Raspberry Pis) to my EC2 sever with MQTT broker. However, as you mentioned in your tutorial the mosquitto_sub client would run indefinitely. If I want to process messages sent from the edge device via MQTT sub/pub system in real time and make requests to another sever, do you think it would be possible with moquitto_sub/mosquitto_pub?

    For example, I want to receive a message from my raspberry pi and everytime my EC2 sever get a new message, I want to make a API request to another website. Is this possible? and how should I do it? Thank you so much!!!

  8. Hi Steve,

    Is it possible to send a publish message with multiple topics and values for each topic?
    I need to send periodically some buffered values. For example, I want to send in the same publish message the topic test/item1 and value 1 and topic test/item2 and value 2.

  9. Thank you Steve for the help
    I am developing a communication system the uses a satellite channel. I am using the Mosquitto clients. On the subscriber side I collect the received messages in a file. To periodically read this file, I have to close de Subscriber client in order to read it and reset it (the code in my application will not allow me delete it or erase its contents while is in use by another application). To close the subscriber client I have the options of the -C switch or Ctrl C. The -C switch does not help as I have to control when the client is closed. And the Ctrl C is a manual option.
    My question is how do I close the subscriber client programmatically?

        1. Steve, the logger does a similar work I do with my code but more efficiently. The log info has to be processed and to do that It has to be read and deleted to start a new reading cycle. Can you reset the log files for each topic (by reset I mean to erase all content), using an external command or program?

          The idea is to monitor the log files periodically for data. If it has data, read the data for processing and erase it leaving the log file empty and ready for new data.

          I can not do that using the mosqutto sub client without closing if first.

          1. You can set the size of the log files and once closed you can delete them using an external program.
            It wouldn’t probably take much of a code change to have the files rotated every day.
            How are you reading the files. i.e python code etc

  10. Hi steve. I’m a developer and I have some few doubts .
    1 ) Which programming language ( Python / Javascript ) is good for IoT Gateway .
    2) How to select database ( SQL / NoSQL ) for IoT project . As per my knowledge mostly we use NoSQL .
    Then when we use SQL .
    3) I have created a IoT gateway in Flask frame work . Is it good to use or else shall I develop it in Django
    framework or in Nodejs using javascript .
    4) How to know the limitations of a IoT gateway/ Platform . Like IoT gateway supports for 1000 devices .
    Can we predict it without connecting to that many devices .

    I will be waiting for your valuable response … Thanks in advance .

    1. Hi
      It all depends on the application and traffic expected. If you really do need speed then you need to go for c or Golang.
      Other than that I would choose the software that you are most comfortable with.
      I have a few basic traffic simulators that you can use for mock traffic.
      Sorry I can’t be more specific than that.

  11. Excellent guidance! Thanks Steve!
    Just a remark. As a beginner (an non-native English) we spell every text line carefully and we are unaware of any required installs.
    I suggest to add that, as a precondition, the “Mosquitto Client package” needs to be installed for the example.
    On any Linux you install with the command: sudo apt-get install mosquitto-clients
    Thanks again! Was very helpfull!

  12. Nice, helpfull.
    Using ssl I get these:

    mosquitto_sub -h -p 8883 -t test -u “93b9f” -P “xxx”

    error:140760FC:SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol

  13. Hi Steve, great tutorial, thanks. I’m using mosquitto on both, PC-Win7 and on my Pi. For both I use Domoticz interface. On my project I have an ESP8266 using ESPEASY with 3 sensors, one BME280 with Idx:4, second as ds18b20 for external temp as Idx:5, and last another ds18b20 for internal temperature with Idx:2. When I use the line command : mosquitto_sub -h localhost -t # or -t domoticz/in I get only the Idx:3 resulut as : {“idx”:3,”nvalue”:0,”svalue”:”20.23;50.81;0;1020.68;0″}
    What’s the syntax to get the others Idx ?

    1. Sorry, in complement I check on ESPEASY then I put a 900 seconds delay, that probably why I don’t see immediately the result. I modify to 30 seconds time elapse and now I’m able to see that :
      domoticz/in {“idx”:4,”nvalue”:0,”svalue”:”12.00″}
      domoticz/in {“idx”:3,”nvalue”:0,”svalue”:”20.19;52.36;0;1020.82;0″}
      domoticz/out {
      “Battery” : 255,
      “RSSI” : 12,
      “description” : “Capteur BME280, Temp├®rature, hygrom├®trie, pression atmosph├®rique.”,
      “dtype” : “Temp + Humidity + Baro”,
      “id” : “82003”,
      “idx” : 3,
      “name” : “Multicapt”,
      “nvalue” : 0,
      “stype” : “THB1 – BTHR918, BTHGN129”,
      “svalue1” : “20.19”,
      “svalue2” : “52.36”,
      “svalue3” : “0”,
      “svalue4” : “1021”,
      “svalue5” : “0”,
      “unit” : 1

      domoticz/out {
      “Battery” : 255,
      “RSSI” : 12,
      “description” : “Capteur BME280, Temp├®rature, hygrom├®trie, pression atmosph├®rique.”,
      “dtype” : “Temp + Humidity + Baro”,
      “id” : “82003”,
      “idx” : 3,
      “name” : “Multicapt”,
      “nvalue” : 0,
      “stype” : “THB1 – BTHR918, BTHGN129”,
      “svalue1” : “20.19”,
      “svalue2” : “52.36”,
      “svalue3” : “0”,
      “svalue4” : “1021”,
      “svalue5” : “0”,
      “unit” : 1

      domoticz/out {
      “Battery” : 255,
      “RSSI” : 12,
      “description” : “Capteur BME280, Temp├®rature, hygrom├®trie, pression atmosph├®rique.”,
      “dtype” : “Temp + Humidity + Baro”,
      “id” : “82003”,
      “idx” : 3,
      “name” : “Multicapt”,
      “nvalue” : 0,
      “stype” : “THB1 – BTHR918, BTHGN129”,
      “svalue1” : “20.19”,
      “svalue2” : “52.36”,
      “svalue3” : “0”,
      “svalue4” : “1021”,
      “svalue5” : “0”,
      “unit” : 1

      domoticz/out {
      “Battery” : 255,
      “RSSI” : 12,
      “description” : “Capteur BME280, Temp├®rature, hygrom├®trie, pression atmosph├®rique.”,
      “dtype” : “Temp + Humidity + Baro”,
      “id” : “82003”,
      “idx” : 3,
      “name” : “Multicapt”,
      “nvalue” : 0,
      “stype” : “THB1 – BTHR918, BTHGN129”,
      “svalue1” : “20.19”,
      “svalue2” : “52.36”,
      “svalue3” : “0”,
      “svalue4” : “1021”,
      “svalue5” : “0”,
      “unit” : 1

      Why is only multiple time only the idx:3 repeat ?
      Is there a way to return only selected item as I.E sValue1, sValue2 and so on ?

    1. Yes but you will need to write the app to do it.
      The receiver must receive the command and then do a system call to execute the command.

  14. Excellent! Very much helpful.

    But I want to send and receive UTF-8 encoded string “∮ E⋅da = Q, n → ∞, ∑ f(i) = ∏ g(i), ∀x∈ℝ: ⌈x⌉ = −⌊−x⌋, α ∧ ¬β = ¬(¬α ∨ β)” using mosquitto_pub and mosquitto_sub applications. Is it possible? If so, Please share the details.

    1. Reading the docs then they support unicode but when I tried it the subscriber only displayed ascii.
      The tools are only really meant for testing and as such I only use them with simple strings.
      If you really do need this then make sure you use the latest versions as they have changed to support some of the features of MQTT version 5. I will do some tests and update the tutorial accordingly.
      This github question/response may be useful.

  15. Great info!
    I have Eclipse Mosquitto installed in a docker container on a Raspberry PI.
    It is working and showing MQTT data. I can use MQTT.fs from a windows 10 system and publish and subscribe.
    But, do not have access to any client tools.
    mosquitto_pub returns command not found. I want to use a python program to send cpu related data via MQTT but need this command. I have tried RPI-mosquitto and eclipse-mosquitto installed in containers with the same results. What am I doing wrong? Thanks

    1. On older windows installs the tools didn’t work and I forget why. They are included with he newer installs and work ok. You could download my install files for windows put them in a folder on the docker image called mos and then change to that directory and run them. There is no need to do any install.
      you can find the files by following this link.
      Let me know if it works ok

  16. HI Steve,
    Thanks for the Great tutorial. i am able to send the messages to the topics.
    Do you have any example use case programs to send data.

  17. Hello steve
    great tutorial
    I am getting this error
    can you tell me what i can do
    error: No connection could be made because the target machine actively refused it.

  18. Hello Steve, thanks for this nice documentation. I ham having some problem with using mosquitto_pub with SSLCertificate. On the client side, when i use:
    mosquitto_pub -h -t test -m “message” -d –cafile certs\ca.crt -p 8883 –insecure
    it shows the following error:
    Client mosqpub|13588-nb2166 sending CONNECT
    Error: A TLS error occurred.
    On the Broker side, it shows the following error:
    1534923031: New connection from on port 8883.
    1534923031: Socket error on client , disconnecting.
    I have already tested the Broker with MQTTfx and there it works fine with certificate. Could you help me out please ?

      1. Yes that is true. it is the same path also added in mosquitto conf in the line cafile.
        and it also shows the following error on the broker side.
        1534933587: New connection from on port 8883.
        1534933587: OpenSSL Error: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca
        1534933587: OpenSSL Error: error:140940E5:SSL routines:ssl3_read_bytes:ssl handshake failure
        1534933587: Socket error on client , disconnecting.

        Is it a problem to use a selfed signed certificate? How to solve this problem?

      2. Hello Steve, I found the issue. It was showing the error that the CA is unknown as i had put the same information in both the information in server and ca crt files. For other users, please do not forget to read the yellow note on this webpage or else you will end up like me. 😉
        In short if you get this error from OpenSSL, it means the certificates are not correct:
        1534938680: New connection from on port 8883.
        1534938680: OpenSSL Error: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca
        1534938680: OpenSSL Error: error:140940E5:SSL routines:ssl3_read_bytes:ssl handshake failure
        1534938680: Socket error on client , disconnecting.
        Now it mosquitto_pub as well as libmosquitto are working correctly. THank you again.

  19. mosquitto_pub -h -p 1883 -t test -m “Electroll”

    when using this command or any other commands with publish and subscribe the ting crashes ,
    receiving messages like “mosquitto_pub.exe stopped working” what should i do
    i also checked netstat -a , port 1883 is present

Leave a Reply to steve Cancel reply

Your email address will not be published. Required fields are marked *