MOSQUITTO_PUB(1)
π¦ MOSQUITTO_PUB(1) β Commands π¦
ok so bestie, you're looking at the man page for mosquitto_pub, which lives in section 1 (Commands) of the manual. pull up a chair, we're doing this π
β¨ NAME β¨
mosquitto_pub β it's an MQTT version 5/3.1.1/3.1 client for publishing simple messages. that's the whole job. one message, one topic, we're out. π
π SYNOPSIS π
mosquitto_pub [options] -t topic {payload-options}
options:
[auth-options] [connection-options] [misc-options]
[mqtt-options] [output-options] [publish-options]
[tls-certificate-options | tls-psk-options]
auth-options:
[-u username] [-P password]
connection-options
{[-h hostname] [--unix socket path] [-p port-number]
| -L URL}
[-A bind-address] [--nodelay] [-S] [--ws]
[--proxy socks-url]
misc-options:
[-o config-file]
mqtt-options:
[-c] [-D command identifier value] [-i client-id]
[-I client-id-prefix] [-k keepalive-time]
[-x session-expiry-interval] [-V protocol-version]
[--will-topic topic [--will-payload payload] [--will-qos qos] [--will-retain]]
output-options:
[-d] [--quiet]
payload-options:
-f file | -l | -m message | -n | -s
publish-options:
[-q message-QoS] [-r] [--repeat count]
[--repeat-delay seconds]
tls-certificate-options:
[--no-tls]
{--cafile file | --capath dir}
[--tls-use-os-certs]
[--cert file] [--key file]
[--ciphers ciphers] [--insecure]
[--tls-alpn protocol] [--tls-keylog file]
[--tls-version version]
[--tls-engine engine]
[--keyform {pem | engine}]
[--tls-engine-kpass-sha1 kpass-sha1]
tls-psk-options:
--psk hex-key --psk-identity identity
[--ciphers ciphers] [--tls-version version]
mosquitto_pub [--help]
like yes it's a lot of brackets, breathe, we'll walk through all of it πΈ
π DESCRIPTION π
mosquitto_pub is a simple MQTT version 5/3.1.1 client that will publish a single message on a topic and then exit. that's it. one and done. main character behavior honestly π
π ENCRYPTED CONNECTIONS π
so this client does support TLS encrypted connections, and bestie, it is strongly recommended that you use an encrypted connection for anything more than the most basic setup. fr fr, don't be out here raw-dogging your network traffic π
to enable TLS connections when you're using x509 certificates, you provide one of either --cafile or --capath as an option.
alternatively β plot twist β if the -p 8883 option is used, then the OS provided certificates will be loaded and neither --cafile nor --capath are needed. the system's got you π«Ά
and to enable TLS connections when using TLS-PSK, you must use the --psk and the --psk-identity options. non-negotiable, both of them, periodt.
β OPTIONS β
okay so there are three ways to feed options to mosquitto_pub: the default config file, a specified config file, or options straight up on the command line. pick your fighter β¨
π Default Config File π
the default config file is located at $XDG_CONFIG_HOME/mosquitto_pub or $HOME/.config/mosquitto_pub on POSIX systems, or %USERPROFILE%\mosquitto_pub on Windows.
the contents of the config file should consist of options, one per line, in the format: -option value. if options are also specified on the command line, those command line options will override the same options set in the config file. the exceptions to this are the message type options, of which only one can be specified. also note that currently some options cannot be negated, e.g. -S. TLS encryption options can be negated with the --no-tls option though, slay.
config file lines that have a # as the first character are treated as comments and not processed any further. classic.
it is suggested that config files are primarily used for authentication purposes β because using a config file lets you authenticate without the need to show the username and password on the command line. which is kind of the whole point, iykyk π₯
π§ Config File π§
available from version 2.1.
a config file can be specified on the command line using -o config-file. if the -o option is used, the default config file will not be loaded. no double-dipping.
the format is the same as for the default config file. π
π The options π
-Aβ bind the outgoing connection to a local ip address/hostname. use this argument if you need to restrict network communication to a particular interface. very "i only talk to my people" of it π-c,--disable-clean-sessionβ disable 'clean session' / enable persistent client mode. when this argument is used, the broker will be instructed not to clean existing sessions for the same client id when the client connects, and sessions will never expire when the client disconnects. MQTT v5 clients can change their session expiry interval with the-xargument.
when a session is persisted on the broker, the subscriptions for the client will be maintained after it disconnects, along with subsequent QoS 1 and QoS 2 messages that arrive. when the client reconnects and does not clean the session, it will receive all of the queued messages. it's giving "i kept your seat at the table" π₯Ί
if using this option, the client id must be set manually with --id. no autopilot here.
--cafileβ define the path to a file containing PEM encoded CA certificates that are trusted. used to enable SSL communication.
see also --capath
--capathβ define the path to a directory containing PEM encoded CA certificates that are trusted. used to enable SSL communication.
for --capath to work correctly, the certificate files must have ".crt" as the file ending and you must run "openssl rehash <path to capath>" each time you add/remove a certificate. yes, each time. don't skip it, it will not work and you'll be sad π
see also --cafile
--certβ define the path to a file containing a PEM encoded certificate for this client, if required by the server.
see also --key and the Encrypted Connections section.
--ciphersβ an openssl compatible list of TLS ciphers to support in the client. seeciphers(1)for more information.-d,--debugβ enable debug messages. turn this on when you want to see everything, she's nosy and we love her π-D,--propertyβ set MQTT v5 properties for with this client. if you use this option, the client will be set to be an MQTT v5 client. heads up, this option has two forms:
-D command identifier value
-D command identifier name value
command is the MQTT command/packet identifier and can be one of CONNECT, PUBLISH, PUBACK, PUBREC, PUBCOMP, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT, AUTH, or WILL. the properties available for each command are listed in the Properties section.
identifier is the name of the property to add. this is as described in the specification, but with - as a word separator. for example: payload-format-indicator. more details are in the Properties section.
value is the value of the property to add, with a data type that is property specific.
name is only used for the user-property property as the first of the two strings in the string pair. in that case, value is the second of the strings in the pair. got it? good, because there will be a quiz π¦
-f,--fileβ send the contents of a file as the message. very demure, very "the file speaks for me".--helpβ display usage information. the classic cry for help but make it documentation π-h,--hostβ specify the host to connect to. defaults tolocalhost.-i,--idβ the id to use for this client. if not given, a client id will be generated depending on the MQTT version being used. for v3.1.1/v3.1, the client generates a client id in the formatmosq-XXXXXXXXXXXXXXXXXX, where theXare replaced with random alphanumeric characters. for v5.0, the client sends a zero length client id, and the server will generate a client id for the client. let the server have a turn, honestly π-I,--id-prefixβ provide a prefix that the client id will be built from by appending the process id of the client. this is useful where the broker is using theclientid_prefixesoption. cannot be used at the same time as the--idargument. pick one, bestie, you can't have both π--insecureβ when using certificate based encryption, this option disables verification of the server hostname in the server certificate. this can be useful when testing initial server configurations but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example.
use this option in testing only. if you need to resort to using this option in a production environment, your setup is at fault and there is no point using encryption. that's not me being mean, that's just the truth π
-k,--keepaliveβ the number of seconds between sending PING commands to the broker for the purposes of informing it we are still connected and functioning. defaults to60seconds. it's the "u up?" text of MQTT πΈ--keyβ define the path to a file containing a PEM encoded private key for this client, carrying out mutual TLS with the server.
see also --cert and the Encrypted Connections section.
--keyformβ specifies the type of private key in use when making TLS connections.. this can be"pem"or"engine". this parameter is useful when a TPM module is being used and the private key has been created with it. defaults to"pem", which means normal private key files are used.
see also --tls-engine.
-L,--urlβ specify specify user, password, hostname, port and topic at once as a URL. the URL must be in the form:mqtt(s)://[username[:password]@]host[:port]/topicorws(s)://[username[:password]@]host[:port]/path
depending on the scheme, the port will default to different values. mqtt:// - 1883, mqtts:// - 8883, ws:// - 80, wss:// - 443. one URL to rule them all π
-l,--stdin-lineβ send messages read from stdin, splitting separate lines into separate messages. line goes in, message comes out β¨-m,--messageβ send a single request message from the command line. the og move.-n,--null-messageβ send a null (zero length) message. sometimes saying nothing is the message, and honestly? iconic π--nodelayβ disable Nagle's algorithm for the socket. this means that latency of sent messages is reduced, which is particularly noticeable for small, reasonably infrequent messages. using this option may result in more packets being sent than would normally be necessary. speed vs. chattiness, you decide π₯--no-tlsβ available from version 2.1.
disable all use of TLS encryption. this is useful if you specify TLS options in a configuration file but want to disable those options. it also stops the automatic use of TLS when connecting to port 8883. very "we're not doing that today" π
-oconfig-file β available from version 2.1.
load options from a config file. see the Default Config File and Config File sections at the start of the Options section. (yes, the ones we literally just read. keeping you oriented π«Ά)
-p,--portβ connect to the port specified. if not given, the default of1883for plain MQTT or8883for MQTT over TLS will be used.-P,--pwβ provide a password to be used for authenticating with the broker. using this argument without also specifying a username is invalid when using MQTT v3.1 or v3.1.1. like, a password with no username? the broker's gonna look at you funny π
see also the --username option.
β¦and that's where part 1 wraps, bestie β more to come, don't go anywhere π
--proxyβ bestie, this lets you route the whole connection through a SOCKS5 proxy. It supports"None"and"username"authentication types. The socks-url has to look likesocks5h://[username[:password]@]host[:port]. Thesocks5hprotocol prefix means the hostnames get resolved by the proxy, not by you. And if the symbols%25,%3Aand%40show up in the username or password, they get URL-decoded into%,:and@respectively. π
If username isn't given, no authentication is attempted at all. If port isn't given, it defaults to 1080.
If host is an IPv6 address it must be wrapped in square brackets, like socks5h://[::1]:1080. Heads up though β square brackets have special meaning in some shells, so the proxy url might need quoting in double or single quotes.
More SOCKS versions may show up in the future depending on demand, and they'll use different protocol prefixes as described in curl(1). β¨
--pskβ drop the hexadecimal pre-shared-key here (no leading0x, okay?) matching the one used on the broker, so you can use TLS-PSK encryption support. You also have to provide--psk-identityto actually enable TLS-PSK. π--psk-identityβ the client identity to use with TLS-PSK support. This may be used instead of a username if the broker is configured to do so. π¦-q,--qosβ pick the quality of service for the message:0,1or2. Defaults to0. π₯--quietβ if you pass this, no runtime errors get printed. Important caveat though: this excludes any error messages given in case of invalid user input (e.g. using--portwithout a port). So bad input still yells at you, sorry babe. π-r,--retainβ with retain, the message gets kept as a"last known good"value on the broker. Seemqtt(7)for more info. Note that zero length payloads are never retained β if you send a zero length payload retained message it will clear any retained message on the topic. Iconic cleanup behaviour honestly. π--repeatβ if the publish mode is-m,-f, or-s(i.e. the modes where only a single message is sent), then--repeatspecifies that the message will be published multiple times. See also--repeat-delay. π--repeat-delayβ if you're using--repeat, the default behaviour is to publish repeated messages as soon as the previous message is delivered. Use--repeat-delayto specify the number of seconds to wait after the previous message was delivered before publishing the next one. Doesn't need to be an integer number of seconds. β
Note that there is no guarantee as to the actual interval between messages β this option simply defines the minimum time from delivery of one message to the start of the publish of the next. No cap on how long it might actually take, bestie.
-s,--stdin-fileβ send a request message read from stdin, sending the entire content as a single message. π«Ά-Sβ use SRV lookups to determine which host to connect to. Performs lookups to_mqtt._tcp.<host>when used in conjunction with-h, otherwise uses_mqtt._tcp.<local dns domain>. π§-t,--topicβ the MQTT topic on which to publish the message. Seemqtt(7)for more information on MQTT topics. πΈ--tls-alpnβ provide a protocol to use when connecting to a broker that has multiple protocols available on a single port, e.g. MQTT and WebSockets. π¦--tls-engineβ a validopensslengine id. These can be listed with theopenssl enginecommand. See also--keyform. β¨--tls-engine-kpass-sha1β SHA1 of the private key password when using a TLS engine. Some TLS engines such as the TPM engine may require the use of a password in order to be accessed. This option lets you hand over a hex encoded SHA1 hash of the password to the engine directly, instead of the user being prompted for the password. See also--tls-engine. π--tls-keylogfile β available from version2.1. Log TLS connection information to file. This option allows tools such astcpdump,wiresharkandmqttsharkto decrypt TLS traffic and inspect the MQTT traffic. In Wireshark this can be done by setting the(Pre)-Master-Secretlog filename option for the Transport Layer Security protocol. π
This option should be used for debugging only, it must not be used in production. Seriously. Not a vibe to ship this. π
--tls-use-os-certsβ if used, this will load and trust the OS provided CA certificates. This can be used in conjunction with--cafileand--capathand can be used on its own to enable TLS mode. This will be set by default if-L mqtts://...is used, or if port is8883and no other certificate options are used. π--tls-versionβ choose which TLS protocol version to use when communicating with the broker. Valid options aretlsv1.3andtlsv1.2. The default value istlsv1.2. Must match the protocol version used by the broker. π-u,--usernameβ provide a username to be used for authenticating with the broker. See also the--pwargument. π--unixβ connect to a broker through a local unix domain socket instead of a TCP socket. This is a replacement for-hand-L. For example:mosquitto_pub --unix /tmp/mosquitto.sock ...See thesocket_domainoption inmosquitto.conf(5)to configure Mosquitto to listen on a unix socket. π§-V,--protocol-versionβ specify which version of the MQTT protocol should be used when connecting to the remote broker. Can be5,311,31, or the more verbosemqttv5,mqttv311, ormqttv31. Defaults to311. β--will-payloadβ specify a message that will be stored by the broker and sent out if this client disconnects unexpectedly. This must be used in conjunction with--will-topic. π«Ά--will-qosβ the QoS to use for the Will. Defaults to0. This must be used in conjunction with--will-topic. π₯--will-retainβ if given, if the client disconnects unexpectedly the message sent out will be treated as a retained message. This must be used in conjunction with--will-topic. π--will-topicβ the topic on which to send a Will, in the event that the client disconnects unexpectedly. π―οΈ--wsβ connect using WebSockets instead of plain TCP. π-xβ set thesession-expiry-intervalproperty on the CONNECT packet. If you use this option, the client will be set to be an MQTT v5 client. Set to0-4294967294to specify the session will expire in that many seconds after the client disconnects, or use-1,4294967295, orβfor a session that does not expire. Defaults to-1if-cis also given, or0if-cnot given. β³
If the session is set to never expire, either with -x or -c, then a client id must be provided.
π―οΈ WILLS π―οΈ
The client can register a message with the broker that will be sent out if it disconnects unexpectedly. See mqtt(7) for more information. π
The minimum requirement for this is to use --will-topic to specify which topic the will should be sent out on. This will result in a non-retained, zero length message with QoS 0.
Use the --will-retain, --will-payload and --will-qos arguments to modify the other will parameters. πΈ
π PROPERTIES π
The -D / --property option allows adding properties to different stages of the mosquitto_pub run. The properties supported for each command are as follows:
β¨ Connect β¨
authentication-data(binary data β note treated as a string)authentication-method(UTF-8 string pair)maximum-packet-size(32-bit unsigned integer)receive-maximum(16-bit unsigned integer)request-problem-information(8-bit unsigned integer)request-response-information(8-bit unsigned integer)session-expiry-interval(32-bit unsigned integer, note use-xinstead)topic-alias-maximum(16-bit unsigned integer)user-property(UTF-8 string pair)
π Publish π
content-type(UTF-8 string)correlation-data(binary data β note treated as a string)message-expiry-interval(32-bit unsigned integer)payload-format-indicator(8-bit unsigned integer)response-topic(UTF-8 string)topic-alias(16-bit unsigned integer)user-property(UTF-8 string pair)
π¦ Disconnect π¦
session-expiry-interval(32-bit unsigned integer)user-property(UTF-8 string pair)
π Will properties π
content-type(UTF-8 string)correlation-data(binary data β note treated as a string)message-expiry-interval(32-bit unsigned integer)payload-format-indicator(8-bit unsigned integer)response-topic(UTF-8 string)user-property(UTF-8 string pair)will-delay-interval(32-bit unsigned integer)
π EXIT STATUS π
Zero on success, or non-zero on error. If the connection is refused by the broker at the MQTT level, then the exit code is the CONNACK reason code. If another error occurs, the exit code is a libmosquitto return value. π€
MQTT v3.1.1 CONNACK codes:
0Success1Connection refused: Bad protocol version2Connection refused: Identifier rejected3Connection refused: Server unavailable4Connection refused: Bad username/password5Connection refused: Not authorized
MQTT v5 CONNACK codes:
0Success128Unspecified error129Malformed packet130Protocol error131Implementation specific error132Unsupported protocol version133Client ID not valid134Bad username or password135Not authorized136Server unavailable137Server busy138Banned139Server shutting down140Bad authentication method141Keep alive timeout142Session taken over143Topic filter invalid144Topic name invalid147Receive maximum exceeded148Topic alias invalid149Packet too large148Message rate too high151Quota exceeded152Administrative action153Payload format invalid154Retain not supported155QoS not supported156Use another server157Server moved158Shared subscriptions not supported159Connection rate exceeded160Maximum connect time161Subscription IDs not supported162Wildcard subscriptions not supported
Other codes:
27Timed out waiting for message πΈ
β¨ EXAMPLES β¨
ok bestie, these are the real-world vibes β copy these, they work π
- Publish temperature information to localhost with QoS 1:
mosquitto_pub -t sensors/temperature -m 32 -q 1
- Publish timestamp and temperature information to a remote host on a non-standard port and QoS 0:
mosquitto_pub -h 192.168.1.1 -p 1885 -t sensors/temperature -m "1266193804 32"
- Publish light switch status. Message is set to retained because there may be a long period of time between light switch events:
mosquitto_pub -r -t switches/kitchen_lights/status -m "on"
- Send the contents of a file in two ways:
mosquitto_pub -t my/topic -f ./data
mosquitto_pub -t my/topic -s < ./data
- Send parsed electricity usage data from a Current Cost meter, reading from stdin with one line/reading as one message:
read_cc128.pl | mosquitto_pub -t sensors/cc128 -l
- Power on an appliance using zigbee2mqtt and an appropriately configured power socket:
mosquitto_pub -t zigbee2mqtt/power-microwave/set -m '{"state":"ON"}'
π FILES π
$XDG_CONFIG_HOME/mosquitto_pub,$HOME/.config/mosquitto_pub,$HOME/snap/mosquitto/current/.config/mosquitto_pub(for snap installs) β configuration file for default options. yeah, that's where your go-to flags live so you don't have to type them every single time π«Ά
π BUGS π
mosquitto bug information can be found at https://github.com/eclipse-mosquitto/mosquitto/issues
not me telling you to go file a bug report β but like, if something's weird, that's the spot π
π SEE ALSO π
mosquitto(7), mqtt(7), mosquitto_rr(1), mosquitto_sub(1), mosquitto(8), libmosquitto(3), mosquitto-tls(7)
like, the whole friend group fr fr π
πΈ AUTHOR πΈ
Roger Light <roger@atchoo.org>
and that's the whole page, bestie!! you ate that π β¨
this iconic little piece of documentation comes from the Mosquitto Project, dated 02/09/2026, and lives at reference MOSQUITTO_PUB(1) β go forth and publish, my love π¦π
π¦ where this page comes from
- alpine 3.24: mosquitto-doc 2.1.2-r1 Β· EPL-1.0 OR EPL-2.0
- fedora 44: mosquitto 2.1.2-1.fc44 Β· EPL-2.0
- fedora 44: mosquitto 2.1.2-1.fc44 Β· EPL-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms