Advertisement
Guest User

Untitled

a guest
May 11th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. #!/usr/bin/env node
  2. /*
  3. * Check an mqtt server by doing a pub/sub
  4. *
  5. * Author: Dave Eddy <dave@daveeddy.com>
  6. * Date: July 13, 2018
  7. * License: MIT
  8. */
  9.  
  10. var getopt = require('posix-getopt');
  11. var mqtt = require('mqtt');
  12.  
  13. function usage() {
  14. console.log('Usage: check_mqtt_server <-t topic> <-S url> [-k] [-U username] [-P password]');
  15. }
  16.  
  17. var parser = new getopt.BasicParser([
  18. 'U:(username)',
  19. 'P:(password)',
  20. 'S:(server)',
  21. 'k(insecure)',
  22. 't:(topic)'
  23. ].join(''), process.argv);
  24.  
  25. var topic;
  26. var url;
  27. var opts = {
  28. clientId: 'nagios-check_mqtt_server'
  29. };
  30. var option;
  31. while ((option = parser.getopt()) !== undefined) {
  32. switch (option.option) {
  33. case 'S':
  34. url = option.optarg;
  35. break;
  36. case 'U':
  37. opts.username = option.optarg;
  38. break;
  39. case 'P':
  40. opts.password = option.optarg;
  41. break;
  42. case 'h':
  43. usage();
  44. process.exit(0);
  45. break;
  46. case 'k':
  47. opts.rejectUnauthorized = false;
  48. break;
  49. case 't':
  50. topic = option.optarg;
  51. break;
  52. default:
  53. usage();
  54. process.exit(1);
  55. break;
  56. }
  57. }
  58.  
  59. if (!url || !topic) {
  60. console.log('unknown: -t <topic> and -S <server> required');
  61. process.exit(3);
  62. }
  63.  
  64. var randomString = Math.random().toString();
  65. var code = 0;
  66.  
  67. var client = mqtt.connect(url, opts);
  68.  
  69. client.on('connect', function () {
  70. client.subscribe(topic);
  71. client.publish(topic, randomString);
  72. });
  73.  
  74. client.on('message', function (_topic, payload) {
  75. var message = payload.toString();
  76.  
  77. if (_topic !== topic) {
  78. // client library malfunction?
  79. console.log('critical: got topic "%s" expected "%s"', _topic, topic);
  80. code = 2;
  81. } else if (message !== randomString) {
  82. console.log('critical: got message "%s" on topic %s expected "%s"',
  83. message, topic, randomString);
  84. code = 2;
  85. } else {
  86. console.log('ok: mqtt server pub/sub working');
  87. code = 0;
  88. }
  89.  
  90. client.end();
  91. });
  92.  
  93. client.on('error', function (err) {
  94. console.log('critical: mqtt server error - %s', err.message);
  95. code = 2;
  96. });
  97.  
  98. client.on('close', function () {
  99. process.exit(code);
  100. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement