Guest User

Untitled

a guest
Dec 11th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. require('dotenv').config()
  2.  
  3. const Promise = require('bluebird')
  4. const WmiClient = require('wmi-client')
  5.  
  6. // let's boiler plate this to use later in the #map
  7. const promisifiedClient = opts => Promise.promisifyAll(new WmiClient(opts))
  8.  
  9. /* wmi queries functions */
  10. async function getWMI(wmi) {
  11. var osVersion = await wmi.queryAsync('SELECT SerialNumber,Caption,Version FROM Win32_OperatingSystem')
  12. var services = await wmi.queryAsync('select Caption, Status, Started, ProcessId, DisplayName, Name, PathName from Win32_Service')
  13. return { osVersion, services }
  14. }
  15.  
  16. // @todo should be getting this from a config file or something
  17. let servers = [
  18. { host:'10.0.10.95', name:'server1', username:process.env.ad_user, password:process.env.ad_pass },
  19. { host:'10.0.10.10', name:'server2', username:process.env.ad_user, password:process.env.ad_pass }
  20. ]
  21.  
  22. /* pass in the servers array so this function itself does not mutate. */
  23. function populateWmiClients(servers) {
  24. // i was wrong, this is not async and doesn't make the connection
  25. // also ALWAYS RETURN THE THING
  26. return servers.map((server) => {
  27. const wmiOptions = {
  28. host: server.host,
  29. username: server.username,
  30. password: server.password,
  31. }
  32. // return a *new* object, not mutating the current ones in place
  33. return Object.assign({}, server, { wmi: promisifiedClient(wmiOptions) })
  34. })
  35. }
  36.  
  37. /* this will be repeating every 5s */
  38. // again, PASS IN THE THING YOU'RE REPLACING, don't mutate in the function
  39. function getWmiData(servers) {
  40. // ALWAYS RETURN YOUR PROMISES
  41. return Promise.map(servers, s => getWMI(s.wmi).then(data => Object.assign({}, s, { data })))
  42. }
  43.  
  44. function updateLoop(oldServers) => {
  45. return getWmiData(oldServers).then((newServers) => {
  46. // @TODO need a function to set these instead of replacing global in place
  47. servers = newServers
  48. // starting at 10 seconds, can always change it
  49. // Object.assign clones servers so you aren't mutating the elements in place
  50. return Promise.delay(10000).then(() => updateLoop(Object.assign({}, servers)))
  51. })
  52. })
  53.  
  54. Promise.try(() => {
  55. return populateWmiClients(servers)
  56. }).then((connectedServers) => {
  57. // connectedServers here is a *new array*, with the clients on each object.. now that we have them all, replace the global state
  58. // @TODO create a state setter function instead of just overwriting it here
  59. servers = connectedServers
  60. }).then(() => {
  61. updateLoop(servers)
  62. })
Add Comment
Please, Sign In to add comment