Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env node
- /*
- * Check an mqtt server by doing a pub/sub
- *
- * Author: Dave Eddy <dave@daveeddy.com>
- * Date: July 13, 2018
- * License: MIT
- */
- var getopt = require('posix-getopt');
- var mqtt = require('mqtt');
- function usage() {
- console.log('Usage: check_mqtt_server <-t topic> <-S url> [-k] [-U username] [-P password]');
- }
- var parser = new getopt.BasicParser([
- 'U:(username)',
- 'P:(password)',
- 'S:(server)',
- 'k(insecure)',
- 't:(topic)'
- ].join(''), process.argv);
- var topic;
- var url;
- var opts = {
- clientId: 'nagios-check_mqtt_server'
- };
- var option;
- while ((option = parser.getopt()) !== undefined) {
- switch (option.option) {
- case 'S':
- url = option.optarg;
- break;
- case 'U':
- opts.username = option.optarg;
- break;
- case 'P':
- opts.password = option.optarg;
- break;
- case 'h':
- usage();
- process.exit(0);
- break;
- case 'k':
- opts.rejectUnauthorized = false;
- break;
- case 't':
- topic = option.optarg;
- break;
- default:
- usage();
- process.exit(1);
- break;
- }
- }
- if (!url || !topic) {
- console.log('unknown: -t <topic> and -S <server> required');
- process.exit(3);
- }
- var randomString = Math.random().toString();
- var code = 0;
- var client = mqtt.connect(url, opts);
- client.on('connect', function () {
- client.subscribe(topic);
- client.publish(topic, randomString);
- });
- client.on('message', function (_topic, payload) {
- var message = payload.toString();
- if (_topic !== topic) {
- // client library malfunction?
- console.log('critical: got topic "%s" expected "%s"', _topic, topic);
- code = 2;
- } else if (message !== randomString) {
- console.log('critical: got message "%s" on topic %s expected "%s"',
- message, topic, randomString);
- code = 2;
- } else {
- console.log('ok: mqtt server pub/sub working');
- code = 0;
- }
- client.end();
- });
- client.on('error', function (err) {
- console.log('critical: mqtt server error - %s', err.message);
- code = 2;
- });
- client.on('close', function () {
- process.exit(code);
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement