meshctrl.js 189 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040
  1. #!/usr/bin/env node
  2. /**
  3. * @description MeshCentral command line tool
  4. * @author Ylian Saint-Hilaire
  5. * @copyright Intel Corporation 2018-2022
  6. * @license Apache-2.0
  7. * @version v0.0.1
  8. */
  9. // Make sure we have the dependency modules
  10. try { require('minimist'); } catch (ex) { console.log('Missing module "minimist", type "npm install minimist" to install it.'); return; }
  11. try { require('ws'); } catch (ex) { console.log('Missing module "ws", type "npm install ws" to install it.'); return; }
  12. var settings = {};
  13. const crypto = require('crypto');
  14. const args = require('minimist')(process.argv.slice(2));
  15. const path = require('path');
  16. const possibleCommands = ['edituser', 'listusers', 'listusersessions', 'listdevicegroups', 'listdevices', 'listusersofdevicegroup', 'listevents', 'logintokens', 'serverinfo', 'userinfo', 'adduser', 'removeuser', 'adddevicegroup', 'removedevicegroup', 'editdevicegroup', 'broadcast', 'showevents', 'addusertodevicegroup', 'removeuserfromdevicegroup', 'addusertodevice', 'removeuserfromdevice', 'sendinviteemail', 'generateinvitelink', 'config', 'movetodevicegroup', 'deviceinfo', 'removedevice', 'editdevice', 'addusergroup', 'listusergroups', 'removeusergroup', 'runcommand', 'shell', 'upload', 'download', 'deviceopenurl', 'devicemessage', 'devicetoast', 'addtousergroup', 'removefromusergroup', 'removeallusersfromusergroup', 'devicesharing', 'devicepower', 'indexagenterrorlog', 'agentdownload', 'report', 'grouptoast', 'groupmessage'];
  17. if (args.proxy != null) { try { require('https-proxy-agent'); } catch (ex) { console.log('Missing module "https-proxy-agent", type "npm install https-proxy-agent" to install it.'); return; } }
  18. if (args['_'].length == 0) {
  19. console.log("MeshCtrl performs command line actions on a MeshCentral server.");
  20. console.log("Information at: https://meshcentral.com");
  21. console.log("No action specified, use MeshCtrl like this:\r\n\r\n meshctrl [action] [arguments]\r\n");
  22. console.log("Supported actions:");
  23. console.log(" Help [action] - Get help on an action.");
  24. console.log(" ServerInfo - Show server information.");
  25. console.log(" UserInfo - Show user information.");
  26. console.log(" ListUsers - List user accounts.");
  27. console.log(" ListUserSessions - List online users.");
  28. console.log(" ListUserGroups - List user groups.");
  29. console.log(" ListDevices - List devices.");
  30. console.log(" ListDeviceGroups - List device groups.");
  31. console.log(" ListUsersOfDeviceGroup - List the users in a device group.");
  32. console.log(" ListEvents - List server events.");
  33. console.log(" LoginTokens - List, create and remove login tokens.");
  34. console.log(" DeviceInfo - Show information about a device.");
  35. console.log(" EditDevice - Make changes to a device.");
  36. console.log(" RemoveDevice - Delete a device.");
  37. console.log(" Config - Perform operation on config.json file.");
  38. console.log(" AddUser - Create a new user account.");
  39. console.log(" EditUser - Change a user account.");
  40. console.log(" RemoveUser - Delete a user account.");
  41. console.log(" AddUserGroup - Create a new user group.");
  42. console.log(" RemoveUserGroup - Delete a user group.");
  43. console.log(" AddToUserGroup - Add a user, device or device group to a user group.");
  44. console.log(" RemoveFromUserGroup - Remove a user, device or device group from a user group.");
  45. console.log(" RemoveAllUsersFromUserGroup - Remove all users from a user group.");
  46. console.log(" AddDeviceGroup - Create a new device group.");
  47. console.log(" RemoveDeviceGroup - Delete a device group.");
  48. console.log(" EditDeviceGroup - Change a device group values.");
  49. console.log(" MoveToDeviceGroup - Move a device to a different device group.");
  50. console.log(" AddUserToDeviceGroup - Add a user to a device group.");
  51. console.log(" RemoveUserFromDeviceGroup - Remove a user from a device group.");
  52. console.log(" AddUserToDevice - Add a user to a device.");
  53. console.log(" RemoveUserFromDevice - Remove a user from a device.");
  54. console.log(" SendInviteEmail - Send an agent install invitation email.");
  55. console.log(" GenerateInviteLink - Create an invitation link.");
  56. console.log(" Broadcast - Display a message to all online users.");
  57. console.log(" ShowEvents - Display real-time server events in JSON format.");
  58. console.log(" RunCommand - Run a shell command on a remote device.");
  59. console.log(" Shell - Access command shell of a remote device.");
  60. console.log(" Upload - Upload a file to a remote device.");
  61. console.log(" Download - Download a file from a remote device.");
  62. console.log(" DeviceOpenUrl - Open a URL on a remote device.");
  63. console.log(" DeviceMessage - Open a message box on a remote device.");
  64. console.log(" DeviceToast - Display a toast notification on a remote device.");
  65. console.log(" GroupMessage - Open a message box on remote devices in a specific device group.");
  66. console.log(" GroupToast - Display a toast notification on remote devices in a specific device group.");
  67. console.log(" DevicePower - Perform wake/sleep/reset/off operations on remote devices.");
  68. console.log(" DeviceSharing - View, add and remove sharing links for a given device.");
  69. console.log(" AgentDownload - Download an agent of a specific type for a device group.");
  70. console.log(" Report - Create and show a CSV report.");
  71. console.log("\r\nSupported login arguments:");
  72. console.log(" --url [wss://server] - Server url, wss://localhost:443 is default.");
  73. console.log(" - Use wss://localhost:443?key=xxx if login key is required.");
  74. console.log(" --loginuser [username] - Login username, admin is default.");
  75. console.log(" --loginpass [password] - Login password OR Leave blank to enter password at prompt");
  76. console.log(" --token [number] - 2nd factor authentication token.");
  77. console.log(" --loginkey [hex] - Server login key in hex.");
  78. console.log(" --loginkeyfile [file] - File containing server login key in hex.");
  79. console.log(" --logindomain [domainid] - Domain id, default is empty, only used with loginkey.");
  80. console.log(" --proxy [http://proxy:123] - Specify an HTTP proxy.");
  81. return;
  82. } else {
  83. settings.cmd = args['_'][0].toLowerCase();
  84. if ((possibleCommands.indexOf(settings.cmd) == -1) && (settings.cmd != 'help')) { console.log("Invalid command. Possible commands are: " + possibleCommands.join(', ') + '.'); return; }
  85. //console.log(settings.cmd);
  86. var ok = false;
  87. switch (settings.cmd) {
  88. case 'config': { performConfigOperations(args); return; }
  89. case 'indexagenterrorlog': { indexAgentErrorLog(); return; }
  90. case 'serverinfo': { ok = true; break; }
  91. case 'userinfo': { ok = true; break; }
  92. case 'listusers': { ok = true; break; }
  93. case 'listusersessions': { ok = true; break; }
  94. case 'listusergroups': { ok = true; break; }
  95. case 'listdevicegroups': { ok = true; break; }
  96. case 'listdevices': { ok = true; break; }
  97. case 'listevents': { ok = true; break; }
  98. case 'logintokens': { ok = true; break; }
  99. case 'listusersofdevicegroup':
  100. case 'deviceinfo':
  101. case 'removedevice':
  102. case 'editdevice': {
  103. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device id, use --id '[deviceid]'")); }
  104. else { ok = true; }
  105. break;
  106. }
  107. case 'addusertodevicegroup': {
  108. if ((args.id == null) && (args.group == null)) { console.log(winRemoveSingleQuotes("Device group identifier missing, use --id '[groupid]' or --group [groupname]")); }
  109. else if (args.userid == null) { console.log("Add user to group missing useid, use --userid [userid]"); }
  110. else { ok = true; }
  111. break;
  112. }
  113. case 'removeuserfromdevicegroup': {
  114. if ((args.id == null) && (args.group == null)) { console.log(winRemoveSingleQuotes("Device group identifier missing, use --id '[groupid]' or --group [groupname]")); }
  115. else if (args.userid == null) { console.log("Remove user from group missing useid, use --userid [userid]"); }
  116. else { ok = true; }
  117. break;
  118. }
  119. case 'addusertodevice': {
  120. if (args.userid == null) { console.log("Add user to device missing userid, use --userid [userid]"); }
  121. else if (args.id == null) { console.log(winRemoveSingleQuotes("Add user to device missing device id, use --id '[deviceid]'")); }
  122. else { ok = true; }
  123. break;
  124. }
  125. case 'removeuserfromdevice': {
  126. if (args.userid == null) { console.log("Remove user from device missing userid, use --userid [userid]"); }
  127. else if (args.id == null) { console.log(winRemoveSingleQuotes("Remove user from device missing device id, use --id '[deviceid]'")); }
  128. else { ok = true; }
  129. break;
  130. }
  131. case 'adddevicegroup': {
  132. if (args.name == null) { console.log("Message group name, use --name [name]"); }
  133. else { ok = true; }
  134. break;
  135. }
  136. case 'editdevicegroup':
  137. case 'removedevicegroup': {
  138. if ((args.id == null) && (args.group == null)) { console.log(winRemoveSingleQuotes("Device group identifier missing, use --id '[groupid]' or --group [groupname]")); }
  139. else { ok = true; }
  140. break;
  141. }
  142. case 'movetodevicegroup': {
  143. if ((args.id == null) && (args.group == null)) { console.log(winRemoveSingleQuotes("Device group identifier missing, use --id '[groupid]' or --group [groupname]")); }
  144. else if (args.devid == null) { console.log(winRemoveSingleQuotes("Device identifier missing, use --devid '[deviceid]'")); }
  145. else { ok = true; }
  146. break;
  147. }
  148. case 'broadcast': {
  149. if (args.msg == null) { console.log("Message missing, use --msg [message]"); }
  150. else { ok = true; }
  151. break;
  152. }
  153. case 'showevents': {
  154. ok = true;
  155. break;
  156. }
  157. case 'adduser': {
  158. if (args.user == null) { console.log("New account name missing, use --user [name]"); }
  159. else if ((args.pass == null) && (args.randompass == null)) { console.log("New account password missing, use --pass [password] or --randompass"); }
  160. else { ok = true; }
  161. break;
  162. }
  163. case 'edituser': {
  164. if (args.userid == null) { console.log("Edit account user missing, use --userid [id]"); }
  165. else { ok = true; }
  166. break;
  167. }
  168. case 'removeuser': {
  169. if (args.userid == null) { console.log("Remove account userid missing, use --userid [id]"); }
  170. else { ok = true; }
  171. break;
  172. }
  173. case 'addusergroup': {
  174. if (args.name == null) { console.log("New user group name missing, use --name [name]"); }
  175. else { ok = true; }
  176. break;
  177. }
  178. case 'removeusergroup': {
  179. if (args.groupid == null) { console.log(winRemoveSingleQuotes("Remove user group id missing, use --groupid '[id]'")); }
  180. else { ok = true; }
  181. break;
  182. }
  183. case 'addtousergroup': {
  184. if (args.groupid == null) { console.log(winRemoveSingleQuotes("Group id missing, use --groupid '[id]'")); }
  185. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing identifier to add, use --id [id]")); }
  186. else { ok = true; }
  187. break;
  188. }
  189. case 'removefromusergroup': {
  190. if (args.groupid == null) { console.log(winRemoveSingleQuotes("Group id missing, use --groupid '[id]'")); }
  191. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing identifier to remove, use --id [id]")); }
  192. else { ok = true; }
  193. break;
  194. }
  195. case 'removeallusersfromusergroup': {
  196. if (args.groupid == null) { console.log(winRemoveSingleQuotes("Group id missing, use --groupid '[id]'")); }
  197. else { ok = true; }
  198. break;
  199. }
  200. case 'sendinviteemail': {
  201. if ((args.id == null) && (args.group == null)) { console.log("Device group identifier missing, use --id '[groupid]' or --group [groupname]"); }
  202. else if (args.email == null) { console.log("Device email is missing, use --email [email]"); }
  203. else { ok = true; }
  204. break;
  205. }
  206. case 'generateinvitelink': {
  207. if ((args.id == null) && (args.group == null)) { console.log("Device group identifier missing, use --id '[groupid]' or --group [groupname]"); }
  208. else if (args.hours == null) { console.log("Invitation validity period missing, use --hours [hours]"); }
  209. else { ok = true; }
  210. break;
  211. }
  212. case 'runcommand': {
  213. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device id, use --id '[deviceid]'")); }
  214. else if (args.run == null) { console.log("Missing run, use --run \"command\""); }
  215. else { ok = true; }
  216. break;
  217. }
  218. case 'shell': {
  219. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device id, use --id '[deviceid]'")); }
  220. else { ok = true; }
  221. break;
  222. }
  223. case 'devicepower': {
  224. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device id, use --id '[deviceid]'")); }
  225. else { ok = true; }
  226. break;
  227. }
  228. case 'devicesharing': {
  229. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device id, use --id '[deviceid]'")); }
  230. else if ((args.daily != null) && (args.weekly != null)) { console.log(winRemoveSingleQuotes("Can't specify both --daily and --weekly at the same time.")); }
  231. else { ok = true; }
  232. break;
  233. }
  234. case 'agentdownload': {
  235. if (args.type == null) { console.log(winRemoveSingleQuotes("Missing device type, use --type [agenttype]")); }
  236. else if ((parseInt(args.type) == null) || isNaN(parseInt(args.type)) || (parseInt(args.type) < 1) || (parseInt(args.type) > 11000)) { console.log(winRemoveSingleQuotes("Invalid agent type, must be a number.")); }
  237. else if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device id, use --id '[meshid]'")); }
  238. else if ((typeof args.id != 'string') || (args.id.length != 64)) { console.log(winRemoveSingleQuotes("Invalid meshid.")); }
  239. else { ok = true; }
  240. break;
  241. }
  242. case 'upload': {
  243. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device id, use --id '[deviceid]'")); }
  244. else if (args.file == null) { console.log("Local file missing, use --file [file] specify the file to upload"); }
  245. else if (args.target == null) { console.log("Remote target path missing, use --target [path] to specify the remote location"); }
  246. else if (require('fs').existsSync(args.file) == false) { console.log("Local file does not exists, check --file"); }
  247. else { ok = true; }
  248. break;
  249. }
  250. case 'download': {
  251. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device id, use --id '[deviceid]'")); }
  252. else if (args.file == null) { console.log("Remote file missing, use --file [file] specify the remote file to download"); }
  253. else if (args.target == null) { console.log("Target path missing, use --target [path] to specify the local download location"); }
  254. else { ok = true; }
  255. break;
  256. }
  257. case 'deviceopenurl': {
  258. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device id, use --id '[deviceid]'")); }
  259. else if (args.openurl == null) { console.log("Remote URL, use --openurl [url] specify the link to open."); }
  260. else { ok = true; }
  261. break;
  262. }
  263. case 'devicemessage': {
  264. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device id, use --id '[deviceid]'")); }
  265. else if (args.msg == null) { console.log("Remote message, use --msg \"[message]\" specify a remote message."); }
  266. else { ok = true; }
  267. break;
  268. }
  269. case 'devicetoast': {
  270. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device id, use --id '[deviceid]'")); }
  271. else if (args.msg == null) { console.log("Remote message, use --msg \"[message]\" specify a remote message."); }
  272. else { ok = true; }
  273. break;
  274. }
  275. case 'groupmessage': {
  276. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device group id, use --id '[devicegroupid]'")); }
  277. else if (args.msg == null) { console.log("Remote message, use --msg \"[message]\" specify a remote message."); }
  278. else { ok = true; }
  279. break;
  280. }
  281. case 'grouptoast': {
  282. if (args.id == null) { console.log(winRemoveSingleQuotes("Missing device group id, use --id '[devicegroupid]'")); }
  283. else if (args.msg == null) { console.log("Remote message, use --msg \"[message]\" specify a remote message."); }
  284. else { ok = true; }
  285. break;
  286. }
  287. case 'report': {
  288. if (args.type == null) { console.log(winRemoveSingleQuotes("Missing report type, use --type '[reporttype]'")); }
  289. else { ok = true; }
  290. break;
  291. }
  292. case 'help': {
  293. if (args['_'].length < 2) {
  294. console.log("Get help on an action. Type:\r\n\r\n help [action]\r\n\r\nPossible actions are: " + possibleCommands.join(', ') + '.');
  295. } else {
  296. switch (args['_'][1].toLowerCase()) {
  297. case 'config': {
  298. displayConfigHelp();
  299. break;
  300. }
  301. case 'sendinviteemail': {
  302. console.log("Send invitation email with instructions on how to install the mesh agent for a specific device group. Example usage:\r\n");
  303. console.log(winRemoveSingleQuotes(" MeshCtrl SendInviteEmail --id 'groupid' --message \"msg\" --email user@sample.com"));
  304. console.log(winRemoveSingleQuotes(" MeshCtrl SendInviteEmail --group \"My Computers\" --name \"Jack\" --email user@sample.com"));
  305. console.log("\r\nRequired arguments:\r\n");
  306. if (process.platform == 'win32') {
  307. console.log(" --id [groupid] - Device group identifier (or --group).");
  308. } else {
  309. console.log(" --id '[groupid]' - Device group identifier (or --group).");
  310. }
  311. console.log(" --group [groupname] - Device group name (or --id).");
  312. console.log(" --email [email] - Email address.");
  313. console.log("\r\nOptional arguments:\r\n");
  314. console.log(" --name (name) - Name of recipient to be included in the email.");
  315. console.log(" --message (msg) - Message to be included in the email.");
  316. break;
  317. }
  318. case 'generateinvitelink': {
  319. console.log("Generate a agent invitation URL for a given group. Example usage:\r\n");
  320. console.log(winRemoveSingleQuotes(" MeshCtrl GenerateInviteLink --id 'groupid' --hours 24"));
  321. console.log(" MeshCtrl GenerateInviteLink --group \"My Computers\" --hours 0");
  322. console.log("\r\nRequired arguments:\r\n");
  323. if (process.platform == 'win32') {
  324. console.log(" --id [groupid] - Device group identifier (or --group).");
  325. } else {
  326. console.log(" --id '[groupid]' - Device group identifier (or --group).");
  327. }
  328. console.log(" --group [groupname] - Device group name (or --id).");
  329. console.log(" --hours [hours] - Validity period in hours or 0 for infinite.");
  330. console.log("\r\nOptional arguments:\r\n");
  331. console.log(" --flags [mode] - Mode flag for link type (0 = both, 1 = interactive only, 2 = background only)");
  332. break;
  333. }
  334. case 'showevents': {
  335. console.log("Show the server's event stream for this user account. Example usage:\r\n");
  336. console.log(" MeshCtrl ShowEvents");
  337. console.log(" MeshCtrl ShowEvents --filter nodeconnect");
  338. console.log(" MeshCtrl ShowEvents --filter uicustomevent,changenode");
  339. console.log("\r\nOptional arguments:\r\n");
  340. console.log(" --filter [actions] - Show only specified actions.");
  341. break;
  342. }
  343. case 'serverinfo': {
  344. console.log("Get information on the MeshCentral server, Example usages:\r\n");
  345. console.log(" MeshCtrl ServerInfo --loginuser myaccountname --loginpass mypassword");
  346. console.log(" MeshCtrl ServerInfo --loginuser myaccountname --loginkeyfile key.txt");
  347. console.log("\r\nOptional arguments:\r\n");
  348. console.log(" --json - Show result as JSON.");
  349. break;
  350. }
  351. case 'userinfo': {
  352. console.log("Get account information for the login account, Example usages:\r\n");
  353. console.log(" MeshCtrl UserInfo --loginuser myaccountname --loginpass mypassword");
  354. console.log(" MeshCtrl UserInfo --loginuser myaccountname --loginkeyfile key.txt");
  355. console.log("\r\nOptional arguments:\r\n");
  356. console.log(" --json - Show result as JSON.");
  357. break;
  358. }
  359. case 'listusers': {
  360. console.log("List the account on the MeshCentral server, Example usages:\r\n");
  361. console.log(" MeshCtrl ListUsers");
  362. console.log(" MeshCtrl ListUsers --json");
  363. console.log(" MeshCtrl ListUsers --nameexists \"bob\"");
  364. console.log(" MeshCtrl ListUsers --filter 2fa");
  365. console.log("\r\nOptional arguments:\r\n");
  366. console.log(" --idexists [id] - Return 1 if id exists, 0 if not.");
  367. console.log(" --nameexists [name] - Return id if name exists.");
  368. console.log(" --filter [filter1,...] - Filter user names: 2FA, NO2FA.");
  369. console.log(" --json - Show result as JSON.");
  370. break;
  371. }
  372. case 'listusersessions': {
  373. console.log("List active user sessions on the MeshCentral server, Example usages:\r\n");
  374. console.log(" MeshCtrl ListUserSessions");
  375. console.log(" MeshCtrl ListUserSessions --json");
  376. break;
  377. }
  378. case 'listusergroups': {
  379. console.log("List user groups on the MeshCentral server, Example usages:\r\n");
  380. console.log(" MeshCtrl ListUserGroups");
  381. console.log(" MeshCtrl ListUserGroups --json");
  382. break;
  383. }
  384. case 'listdevicegroups': {
  385. console.log("List the device groups for this account. Example usages:\r\n");
  386. console.log(" MeshCtrl ListDeviceGroups ");
  387. console.log(" MeshCtrl ListDeviceGroups --json");
  388. console.log("\r\nOptional arguments:\r\n");
  389. console.log(" --idexists [id] - Return 1 if id exists, 0 if not.");
  390. console.log(" --nameexists [name] - Return id if name exists.");
  391. console.log(" --emailexists [email] - Return id if email exists.");
  392. console.log(" --hex - Display meshid in hex format.");
  393. console.log(" --json - Show result as JSON.");
  394. break;
  395. }
  396. case 'listdevices': {
  397. console.log("List devices. Example usages:\r\n");
  398. console.log(" MeshCtrl ListDevices");
  399. console.log(winRemoveSingleQuotes(" MeshCtrl ListDevices -id '[groupid]' --json"));
  400. console.log("\r\nOptional arguments:\r\n");
  401. if (process.platform == 'win32') {
  402. console.log(" --id [groupid] - Filter by group identifier (or --group).");
  403. } else {
  404. console.log(" --id '[groupid]' - Filter by group identifier (or --group).");
  405. }
  406. console.log(" --group [groupname] - Filter by group name (or --id).");
  407. console.log(" --count - Only return the device count.");
  408. console.log(" --json - Show result as JSON.");
  409. console.log(" --csv - Show result as comma separated values.");
  410. console.log(" --filter \"[filter]\" - Filter devices using a filter string.");
  411. console.log(" \"x\" - Devices with \"x\" in the name.");
  412. console.log(" \"user:x or u:x\" - Devices with \"x\" in the name of currently logged in user.");
  413. console.log(" \"ip:x\" - Devices \"x\" IP address.");
  414. console.log(" \"group:x or g:x\" - Devices with \"x\" in device group name.");
  415. console.log(" \"tag:x or t:x\" - Devices with \"x\" in device tag.");
  416. console.log(" \"atag:x or a:x\" - Devices with \"x\" in device agent tag.");
  417. console.log(" \"os:x\" - Devices with \"x\" in the device OS description.");
  418. console.log(" \"amt:x\" - Devices with Intel AMT provisioning state (0, 1, 2).");
  419. console.log(" \"desc:x\" - Devices with \"x\" in device description.");
  420. console.log(" \"wsc:ok\" - Devices with Windows Security Center ok.");
  421. console.log(" \"wsc:noav\" - Devices with Windows Security Center with anti-virus problem.");
  422. console.log(" \"wsc:noupdate\" - Devices with Windows Security Center with update problem.");
  423. console.log(" \"wsc:nofirewall\" - Devices with Windows Security Center with firewall problem.");
  424. console.log(" \"wsc:any\" - Devices with Windows Security Center with any problem.");
  425. console.log(" \"a and b\" - Match both conditions with precedence over OR. For example: \"lab and g:home\".");
  426. console.log(" \"a or b\" - Math one of the conditions, for example: \"lab or g:home\".");
  427. console.log(" --filterid [id,id...] - Show only results for devices with included id.");
  428. console.log(" --details - Show all device details.");
  429. break;
  430. }
  431. case 'listusersofdevicegroup': {
  432. console.log("List users that have permissions for a given device group. Example usage:\r\n");
  433. console.log(" MeshCtrl ListUserOfDeviceGroup ");
  434. console.log("\r\nRequired arguments:\r\n");
  435. if (process.platform == 'win32') {
  436. console.log(" --id [groupid] - Device group identifier.");
  437. } else {
  438. console.log(" --id '[groupid]' - Device group identifier.");
  439. }
  440. console.log("\r\nOptional arguments:\r\n");
  441. console.log(" --json - Show result as JSON.");
  442. break;
  443. }
  444. case 'listevents': {
  445. console.log("List server events optionally filtered by user or device. Example usage:\r\n");
  446. console.log(" MeshCtrl ListEvents ");
  447. console.log("\r\nOptional arguments:\r\n");
  448. console.log(" --userid [name] - User account identifier.");
  449. console.log(" --id [deviceid] - The device identifier.");
  450. console.log(" --limit [number] - Maximum number of events to list.");
  451. console.log(" --raw - Output raw data in JSON format.");
  452. console.log(" --json - Give results in JSON format.");
  453. break;
  454. }
  455. case 'logintokens': {
  456. console.log("List account login tokens and allow addition and removal. Example usage:\r\n");
  457. console.log(" MeshCtrl LoginTokens ");
  458. console.log("\r\nOptional arguments:\r\n");
  459. console.log(" --remove [name] - Remove a login token.");
  460. console.log(" --add [name] - Add a login token.");
  461. console.log(" --expire [minutes] - When adding a token, minutes until expire.");
  462. console.log(" --json - Show login tokens in JSON format.");
  463. break;
  464. }
  465. case 'adduser': {
  466. console.log("Add a new user account. Example usages:\r\n");
  467. console.log(" MeshCtrl AddUser --user newaccountname --pass newpassword");
  468. console.log(" MeshCtrl AddUser --user newaccountname --randompass --rights full");
  469. console.log("\r\nRequired arguments:\r\n");
  470. console.log(" --user [name] - New account name.");
  471. console.log(" --pass [password] - New account password.");
  472. console.log(" --randompass - Create account with a random password.");
  473. console.log("\r\nOptional arguments:\r\n");
  474. console.log(" --domain [domain] - Account domain, only for cross-domain admins.");
  475. console.log(" --email [email] - New account email address.");
  476. console.log(" --emailverified - New account email is verified.");
  477. console.log(" --resetpass - Request password reset on next login.");
  478. console.log(" --realname [name] - Set the real name for this account.");
  479. console.log(" --phone [number] - Set the account phone number.");
  480. console.log(" --rights [none|full|a,b,c] - Comma separated list of server permissions. Possible values:");
  481. console.log(" manageusers,serverbackup,serverrestore,serverupdate,fileaccess,locked,nonewgroups,notools,usergroups,recordings,locksettings,allevents,nonewdevices");
  482. break;
  483. }
  484. case 'edituser': {
  485. console.log("Edit a user account, Example usages:\r\n");
  486. console.log(" MeshCtrl EditUser --userid user --rights locked,locksettings");
  487. console.log(" MeshCtrl EditUser --userid user --realname Jones");
  488. console.log("\r\nRequired arguments:\r\n");
  489. console.log(" --userid [name] - User account identifier.");
  490. console.log("\r\nOptional arguments:\r\n");
  491. console.log(" --domain [domain] - Account domain, only for cross-domain admins.");
  492. console.log(" --email [email] - Account email address.");
  493. console.log(" --emailverified - Account email is verified.");
  494. console.log(" --resetpass - Request password reset on next login.");
  495. console.log(" --realname [name] - Set the real name for this account.");
  496. console.log(" --phone [number] - Set the account phone number.");
  497. console.log(" --rights [none|full|a,b,c] - Comma separated list of server permissions. Possible values:");
  498. console.log(" manageusers,serverbackup,serverrestore,serverupdate,fileaccess,locked,nonewgroups,notools,usergroups,recordings,locksettings,allevents,nonewdevices");
  499. break;
  500. }
  501. case 'removeuser': {
  502. console.log("Delete a user account, Example usages:\r\n");
  503. console.log(" MeshCtrl RemoveUser --userid accountid");
  504. console.log("\r\nRequired arguments:\r\n");
  505. console.log(" --userid [id] - Account identifier.");
  506. break;
  507. }
  508. case 'addusergroup': {
  509. console.log("Create a new user group, Example usages:\r\n");
  510. console.log(" MeshCtrl AddUserGroup --name \"Test Group\"");
  511. console.log("\r\nRequired arguments:\r\n");
  512. console.log(" --name [name] - Name of the user group.");
  513. break;
  514. }
  515. case 'removeusergroup': {
  516. console.log("Remove a user group, Example usages:\r\n");
  517. console.log(winRemoveSingleQuotes(" MeshCtrl RemoveUserGroup --groupid 'ugrp//abcdf'"));
  518. console.log("\r\nRequired arguments:\r\n");
  519. if (process.platform == 'win32') {
  520. console.log(" --groupid [groupid] - User group identifier.");
  521. } else {
  522. console.log(" --groupid '[groupid]' - User group identifier.");
  523. }
  524. break;
  525. }
  526. case 'addtousergroup': {
  527. console.log("Add a user, device or device group to a user group, Example usages:\r\n");
  528. console.log(winRemoveSingleQuotes(" MeshCtrl AddToUserGroup --id 'user//abcdef' --groupid 'ugrp//abcdf'"));
  529. console.log(winRemoveSingleQuotes(" MeshCtrl AddToUserGroup --id 'node//abcdef' --groupid 'ugrp//abcdf' --rights [rights]"));
  530. console.log(winRemoveSingleQuotes(" MeshCtrl AddToUserGroup --id 'mesh//abcdef' --groupid 'ugrp//abcdf' --rights [rights]"));
  531. console.log("\r\nRequired arguments:\r\n");
  532. if (process.platform == 'win32') {
  533. console.log(" --id [id] - Identifier to add.");
  534. console.log(" --groupid [groupid] - User group identifier.");
  535. } else {
  536. console.log(" --id '[id]' - Identifier to add.");
  537. console.log(" --groupid '[groupid]' - User group identifier.");
  538. }
  539. console.log("\r\nOptional arguments:\r\n");
  540. console.log(" --rights [number] - Rights granted for adding device or device group.");
  541. console.log(" - 4294967295 for full admin or the sum of the following numbers.");
  542. console.log(" 1 = Edit Device Group 2 = Manage Users ");
  543. console.log(" 4 = Manage Computers 8 = Remote Control ");
  544. console.log(" 16 = Agent Console 32 = Server Files ");
  545. console.log(" 64 = Wake Device 128 = Set Notes ");
  546. console.log(" 256 = Remote View Only 512 = No Terminal ");
  547. console.log(" 1024 = No Files 2048 = No Intel AMT ");
  548. console.log(" 4096 = Desktop Limited Input 8192 = Limit Events ");
  549. console.log(" 16384 = Chat / Notify 32768 = Uninstall Agent ");
  550. console.log(" 65536 = No Remote Desktop 131072 = Remote Commands ");
  551. console.log(" 262144 = Reset / Power off ");
  552. break;
  553. }
  554. case 'removefromusergroup': {
  555. console.log("Remove a user, device or device group from a user group, Example usages:\r\n");
  556. console.log(winRemoveSingleQuotes(" MeshCtrl RemoveUserFromUserGroup --userid 'user//abcdef' --groupid 'ugrp//abcdf'"));
  557. console.log(winRemoveSingleQuotes(" MeshCtrl RemoveUserFromUserGroup --userid 'node//abcdef' --groupid 'ugrp//abcdf'"));
  558. console.log(winRemoveSingleQuotes(" MeshCtrl RemoveUserFromUserGroup --userid 'mesh//abcdef' --groupid 'ugrp//abcdf'"));
  559. console.log("\r\nRequired arguments:\r\n");
  560. if (process.platform == 'win32') {
  561. console.log(" --id [userid] - Identifier to remove.");
  562. console.log(" --groupid [groupid] - User group identifier.");
  563. } else {
  564. console.log(" --id '[userid]' - Identifier to remove.");
  565. console.log(" --groupid '[groupid]' - User group identifier.");
  566. }
  567. break;
  568. }
  569. case 'removeallusersfromusergroup': {
  570. console.log("Remove all users from a user group, Example usages:\r\n");
  571. console.log(winRemoveSingleQuotes(" MeshCtrl RemoveAllUsersFromUserGroup --groupid 'ugrp//abcdf'"));
  572. console.log("\r\nRequired arguments:\r\n");
  573. if (process.platform == 'win32') {
  574. console.log(" --groupid [groupid] - User group identifier.");
  575. } else {
  576. console.log(" --groupid '[groupid]' - User group identifier.");
  577. }
  578. break;
  579. }
  580. case 'adddevicegroup': {
  581. console.log("Add a device group, Example usages:\r\n");
  582. console.log(" MeshCtrl AddDeviceGroup --name newgroupname");
  583. console.log(" MeshCtrl AddDeviceGroup --name newgroupname --desc description --amtonly");
  584. console.log(" MeshCtrl AddDeviceGroup --name newgroupname --features 1 --consent 7");
  585. console.log("\r\nRequired arguments:\r\n");
  586. console.log(" --name [name] - Name of the new group.");
  587. console.log("\r\nOptional arguments:\r\n");
  588. console.log(" --desc [description] - New group description.");
  589. console.log(" --amtonly - New group is agent-less, Intel AMT only.");
  590. console.log(" --agentless - New group is agent-less only.");
  591. console.log(" --features [number] - Set device group features, sum of numbers below.");
  592. console.log(" 1 = Auto-Remove 2 = Hostname Sync");
  593. console.log(" 4 = Record Sessions");
  594. console.log(" --consent [number] - Set device group user consent, sum of numbers below.");
  595. console.log(" 1 = Desktop notify user 2 = Terminal notify user ");
  596. console.log(" 4 = Files notify user 8 = Desktop prompt user ");
  597. console.log(" 16 = Terminal prompt user 32 = Files prompt user ");
  598. console.log(" 64 = Desktop Toolbar ");
  599. break;
  600. }
  601. case 'removedevicegroup': {
  602. console.log("Remove a device group, Example usages:\r\n");
  603. console.log(winRemoveSingleQuotes(" MeshCtrl RemoveDeviceGroup --id 'groupid'"));
  604. console.log("\r\nRequired arguments:\r\n");
  605. if (process.platform == 'win32') {
  606. console.log(" --id [groupid] - Device group identifier (or --group).");
  607. } else {
  608. console.log(" --id '[groupid]' - Device group identifier (or --group).");
  609. }
  610. console.log(" --group [groupname] - Device group name (or --id).");
  611. break;
  612. }
  613. case 'editdevicegroup': {
  614. console.log("Edit a device group, Example usages:\r\n");
  615. console.log(winRemoveSingleQuotes(" MeshCtrl EditDeviceGroup --id 'groupid' --name \"New Name\""));
  616. console.log(winRemoveSingleQuotes(" MeshCtrl EditDeviceGroup --id 'groupid' --desc \"Description\" --consent 63"));
  617. console.log(winRemoveSingleQuotes(" MeshCtrl EditDeviceGroup --id 'groupid' --invitecodes \"code1,code2\" --backgroundonly"));
  618. console.log("\r\nRequired arguments:\r\n");
  619. if (process.platform == 'win32') {
  620. console.log(" --id [groupid] - Device group identifier (or --group).");
  621. } else {
  622. console.log(" --id '[groupid]' - Device group identifier (or --group).");
  623. }
  624. console.log(" --group [groupname] - Device group name (or --id).");
  625. console.log("\r\nOptional arguments:\r\n");
  626. console.log(" --name [name] - Set new device group name.");
  627. console.log(" --desc [description] - Set new device group description, blank to clear.");
  628. console.log(" --flags [number] - Set device group flags, sum of the values below, 0 for none.");
  629. console.log(" 1 = Auto remove device on disconnect.");
  630. console.log(" 2 = Sync hostname.");
  631. console.log(" --consent [number] - Set device group consent options, sum of the values below, 0 for none.");
  632. console.log(" 1 = Desktop notify user.");
  633. console.log(" 2 = Terminal notify user.");
  634. console.log(" 4 = Files notify user.");
  635. console.log(" 8 = Desktop prompt for user consent.");
  636. console.log(" 16 = Terminal prompt for user consent.");
  637. console.log(" 32 = Files prompt for user consent.");
  638. console.log(" 64 = Desktop show connection toolbar.");
  639. console.log(" --invitecodes [aa,bb] - Comma separated list of invite codes, blank to clear.");
  640. console.log(" --backgroundonly - When used with invitecodes, set agent to only install in background.");
  641. console.log(" --interactiveonly - When used with invitecodes, set agent to only run on demand.");
  642. break;
  643. }
  644. case 'movetodevicegroup': {
  645. console.log("Move a device to a new device group, Example usages:\r\n");
  646. console.log(winRemoveSingleQuotes(" MeshCtrl MoveToDeviceGroup --devid 'deviceid' --id 'groupid'"));
  647. console.log("\r\nRequired arguments:\r\n");
  648. if (process.platform == 'win32') {
  649. console.log(" --id [groupid] - Device group identifier (or --group).");
  650. } else {
  651. console.log(" --id '[groupid]' - Device group identifier (or --group).");
  652. }
  653. console.log(" --group [groupname] - Device group name (or --id).");
  654. if (process.platform == 'win32') {
  655. console.log(" --devid [deviceid] - Device identifier.");
  656. } else {
  657. console.log(" --devid '[deviceid]' - Device identifier.");
  658. }
  659. break;
  660. }
  661. case 'addusertodevicegroup': {
  662. console.log("Add a user to a device group, Example usages:\r\n");
  663. console.log(winRemoveSingleQuotes(" MeshCtrl AddUserToDeviceGroup --id 'groupid' --userid userid --fullrights"));
  664. console.log(" MeshCtrl AddUserToDeviceGroup --group groupname --userid userid --editgroup --manageusers");
  665. console.log("\r\nRequired arguments:\r\n");
  666. if (process.platform == 'win32') {
  667. console.log(" --id [groupid] - Device group identifier (or --group).");
  668. } else {
  669. console.log(" --id '[groupid]' - Device group identifier (or --group).");
  670. }
  671. console.log(" --group [groupname] - Device group name (or --id).");
  672. console.log(" --userid [userid] - The user identifier.");
  673. console.log("\r\nOptional arguments:\r\n");
  674. console.log(" --fullrights - Allow full rights over this device group.");
  675. console.log(" --editgroup - Allow the user to edit group information.");
  676. console.log(" --manageusers - Allow the user to add/remove users.");
  677. console.log(" --managedevices - Allow the user to edit device information.");
  678. console.log(" --remotecontrol - Allow device remote control operations.");
  679. console.log(" --agentconsole - Allow agent console operations.");
  680. console.log(" --serverfiles - Allow access to group server files.");
  681. console.log(" --wakedevices - Allow device wake operation.");
  682. console.log(" --notes - Allow editing of device notes.");
  683. console.log(" --desktopviewonly - Restrict user to view-only remote desktop.");
  684. console.log(" --limiteddesktop - Limit remote desktop keys.");
  685. console.log(" --noterminal - Hide the terminal tab from this user.");
  686. console.log(" --nofiles - Hide the files tab from this user.");
  687. console.log(" --noamt - Hide the Intel AMT tab from this user.");
  688. console.log(" --limitedevents - User can only see his own events.");
  689. console.log(" --chatnotify - Allow chat and notification options.");
  690. console.log(" --uninstall - Allow remote uninstall of the agent.");
  691. if (args.limiteddesktop) { meshrights |= 4096; }
  692. if (args.limitedevents) { meshrights |= 8192; }
  693. if (args.chatnotify) { meshrights |= 16384; }
  694. if (args.uninstall) { meshrights |= 32768; }
  695. break;
  696. }
  697. case 'removeuserfromdevicegroup': {
  698. console.log("Remove a user from a device group, Example usages:\r\n");
  699. console.log(winRemoveSingleQuotes(" MeshCtrl RemoveuserFromDeviceGroup --id 'groupid' --userid userid"));
  700. console.log("\r\nRequired arguments:\r\n");
  701. if (process.platform == 'win32') {
  702. console.log(" --id [groupid] - Device group identifier (or --group).");
  703. } else {
  704. console.log(" --id '[groupid]' - Device group identifier (or --group).");
  705. }
  706. console.log(" --group [groupname] - Device group name (or --id).");
  707. console.log(" --userid [userid] - The user identifier.");
  708. break;
  709. }
  710. case 'addusertodevice': {
  711. console.log("Add a user to a device, Example usages:\r\n");
  712. console.log(winRemoveSingleQuotes(" MeshCtrl AddUserToDevice --id 'deviceid' --userid userid --fullrights"));
  713. console.log(winRemoveSingleQuotes(" MeshCtrl AddUserToDevice --id 'deviceid' --userid userid --remotecontrol"));
  714. console.log("\r\nRequired arguments:\r\n");
  715. if (process.platform == 'win32') {
  716. console.log(" --id [deviceid] - The device identifier.");
  717. } else {
  718. console.log(" --id '[deviceid]' - The device identifier.");
  719. }
  720. console.log(" --userid [userid] - The user identifier.");
  721. console.log("\r\nOptional arguments:\r\n");
  722. console.log(" --fullrights - Allow full rights over this device.");
  723. console.log(" --remotecontrol - Allow device remote control operations.");
  724. console.log(" --agentconsole - Allow agent console operations.");
  725. console.log(" --serverfiles - Allow access to group server files.");
  726. console.log(" --wakedevices - Allow device wake operation.");
  727. console.log(" --notes - Allow editing of device notes.");
  728. console.log(" --desktopviewonly - Restrict user to view-only remote desktop.");
  729. console.log(" --limiteddesktop - Limit remote desktop keys.");
  730. console.log(" --noterminal - Hide the terminal tab from this user.");
  731. console.log(" --nofiles - Hide the files tab from this user.");
  732. console.log(" --noamt - Hide the Intel AMT tab from this user.");
  733. console.log(" --limitedevents - User can only see his own events.");
  734. console.log(" --chatnotify - Allow chat and notification options.");
  735. console.log(" --uninstall - Allow remote uninstall of the agent.");
  736. break;
  737. }
  738. case 'removeuserfromdevice': {
  739. console.log("Remove a user from a device, Example usages:\r\n");
  740. console.log(winRemoveSingleQuotes(" MeshCtrl RemoveuserFromDeviceGroup --id 'deviceid' --userid userid"));
  741. console.log("\r\nRequired arguments:\r\n");
  742. if (process.platform == 'win32') {
  743. console.log(" --id [deviceid] - The device identifier.");
  744. } else {
  745. console.log(" --id '[deviceid]' - The device identifier.");
  746. }
  747. console.log(" --userid [userid] - The user identifier.");
  748. break;
  749. }
  750. case 'broadcast': {
  751. console.log("Display a message to one or all logged in users, Example usages:\r\n");
  752. console.log(" MeshCtrl Broadcast --msg \"This is a test\"");
  753. console.log("\r\nRequired arguments:\r\n");
  754. console.log(" --msg [message] - Message to display.");
  755. console.log("\r\nOptional arguments:\r\n");
  756. console.log(" --user [userid] - Send the message to the specified user.");
  757. break;
  758. }
  759. case 'deviceinfo': {
  760. console.log("Display information about a device, Example usages:\r\n");
  761. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceInfo --id 'deviceid'"));
  762. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceInfo --id 'deviceid' --json"));
  763. console.log("\r\nRequired arguments:\r\n");
  764. if (process.platform == 'win32') {
  765. console.log(" --id [deviceid] - The device identifier.");
  766. } else {
  767. console.log(" --id '[deviceid]' - The device identifier.");
  768. }
  769. console.log("\r\nOptional arguments:\r\n");
  770. console.log(" --raw - Output raw data in JSON format.");
  771. console.log(" --json - Give results in JSON format.");
  772. break;
  773. }
  774. case 'removedevice': {
  775. console.log("Delete a device, Example usages:\r\n");
  776. console.log(winRemoveSingleQuotes(" MeshCtrl RemoveDevice --id 'deviceid'"));
  777. console.log("\r\nRequired arguments:\r\n");
  778. if (process.platform == 'win32') {
  779. console.log(" --id [deviceid] - The device identifier.");
  780. } else {
  781. console.log(" --id '[deviceid]' - The device identifier.");
  782. }
  783. break;
  784. }
  785. case 'editdevice': {
  786. console.log("Change information about a device, Example usages:\r\n");
  787. console.log(winRemoveSingleQuotes(" MeshCtrl EditDevice --id 'deviceid' --name 'device1'"));
  788. console.log("\r\nRequired arguments:\r\n");
  789. if (process.platform == 'win32') {
  790. console.log(" --id [deviceid] - The device identifier.");
  791. } else {
  792. console.log(" --id '[deviceid]' - The device identifier.");
  793. }
  794. console.log("\r\nOptional arguments:\r\n");
  795. if (process.platform == 'win32') {
  796. console.log(" --name [name] - Change device name.");
  797. console.log(" --desc [description] - Change device description.");
  798. console.log(" --tags [tag1,tags2] - Change device tags.");
  799. } else {
  800. console.log(" --name '[name]' - Change device name.");
  801. console.log(" --desc '[description]' - Change device description.");
  802. console.log(" --tags '[tag1,tags2]' - Change device tags.");
  803. }
  804. console.log(" --icon [number] - Change the device icon (1 to 8).");
  805. console.log(" --consent [flags] - Sum of the following numbers:");
  806. console.log(" 1 = Desktop notify 2 = Terminal notify");
  807. console.log(" 4 = Files notify 8 = Desktop prompt");
  808. console.log(" 16 = Terminal prompt 32 = Files prompt");
  809. console.log(" 64 = Desktop privacy bar");
  810. break;
  811. }
  812. case 'runcommand': {
  813. console.log("Run a shell command on a remote device, Example usages:\r\n");
  814. console.log(winRemoveSingleQuotes(" MeshCtrl RunCommand --id 'deviceid' --run \"command\""));
  815. console.log(winRemoveSingleQuotes(" MeshCtrl RunCommand --id 'deviceid' --run \"command\" --powershell"));
  816. console.log(winRemoveSingleQuotes(" MeshCtrl RunCommand --id 'deviceid' --run \"command\" --reply"));
  817. console.log("\r\nRequired arguments:\r\n");
  818. if (process.platform == 'win32') {
  819. console.log(" --id [deviceid] - The device identifier.");
  820. } else {
  821. console.log(" --id '[deviceid]' - The device identifier.");
  822. }
  823. console.log(" --run \"[command]\" - Shell command to execute on the remote device.");
  824. console.log("\r\nOptional arguments:\r\n");
  825. console.log(" --powershell - Run in Windows PowerShell.");
  826. console.log(" --runasuser - Attempt to run the command as logged in user.");
  827. console.log(" --runasuseronly - Only run the command as the logged in user.");
  828. console.log(" --reply - Return with the output from running the command.");
  829. break;
  830. }
  831. case 'shell': {
  832. console.log("Access a command shell on a remote device, Example usages:\r\n");
  833. console.log(winRemoveSingleQuotes(" MeshCtrl Shell --id 'deviceid'"));
  834. console.log(winRemoveSingleQuotes(" MeshCtrl Shell --id 'deviceid' --powershell"));
  835. console.log("\r\nRequired arguments:\r\n");
  836. if (process.platform == 'win32') {
  837. console.log(" --id [deviceid] - The device identifier.");
  838. } else {
  839. console.log(" --id '[deviceid]' - The device identifier.");
  840. }
  841. console.log("\r\nOptional arguments:\r\n");
  842. console.log(" --powershell - Run a Windows PowerShell.");
  843. break;
  844. }
  845. case 'devicepower': {
  846. console.log("Perform power operations on remote devices, Example usages:\r\n");
  847. console.log(winRemoveSingleQuotes(" MeshCtrl DevicePower --wake --id 'deviceid'"));
  848. console.log(winRemoveSingleQuotes(" MeshCtrl DevicePower --sleep --id 'deviceid'"));
  849. console.log(winRemoveSingleQuotes(" MeshCtrl DevicePower --reset --id 'deviceid'"));
  850. console.log(winRemoveSingleQuotes(" MeshCtrl DevicePower --off --id 'deviceid1,deviceid2'"));
  851. console.log("\r\nNote that some power operations may take up to a minute to execute.\r\n");
  852. console.log("Required arguments:\r\n");
  853. if (process.platform == 'win32') {
  854. console.log(" --id [deviceid1,deviceid2] - Device identifiers.");
  855. } else {
  856. console.log(" --id '[deviceid1,deviceid2]' - Device identifiers.");
  857. }
  858. console.log("\r\nOptional arguments:\r\n");
  859. console.log(" --wake - Attempt to wake up the remote device.");
  860. console.log(" --reset - Attempt to remote the remote device.");
  861. console.log(" --sleep - Attempt to place the remote device in low power mode.");
  862. console.log(" --off - Attempt to power off the remote device.");
  863. console.log(" --amtoff - Attempt to power off the remote device using Intel AMT.");
  864. console.log(" --amton - Attempt to power on the remote device using Intel AMT.");
  865. console.log(" --amtreset - Attempt to reset the remote device using Intel AMT.");
  866. break;
  867. }
  868. case 'devicesharing': {
  869. var tzoffset = (new Date()).getTimezoneOffset() * 60000; // Offset in milliseconds
  870. var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -5);
  871. console.log("List sharing links for a specified device, Example usages:\r\n");
  872. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceSharing --id 'deviceid'"));
  873. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceSharing --id 'deviceid' --remove abcdef"));
  874. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceSharing --id 'deviceid' --add Guest --start " + localISOTime + " --duration 30"));
  875. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceSharing --id 'deviceid' --add Guest --start " + localISOTime + " --duration 30 --daily"));
  876. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceSharing --id 'deviceid' --add Guest --type desktop,terminal --consent prompt"));
  877. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceSharing --id 'deviceid' --add Guest --type http --port 80"));
  878. console.log("\r\nRequired arguments:\r\n");
  879. if (process.platform == 'win32') {
  880. console.log(" --id [deviceid] - The device identifier.");
  881. } else {
  882. console.log(" --id '[deviceid]' - The device identifier.");
  883. }
  884. console.log("\r\nOptional arguments:\r\n");
  885. console.log(" --remove [shareid] - Remove a device sharing link.");
  886. console.log(" --add [guestname] - Add a device sharing link.");
  887. console.log(" --type [desktop,terminal,files,http,https] - Type of sharing to add, can be combined. default is desktop.");
  888. console.log(" --viewonly - Make desktop sharing view only.");
  889. console.log(" --consent [notify,prompt,none] - Consent flags, default is notify.");
  890. console.log(" --start [yyyy-mm-ddThh:mm:ss] - Start time, default is now.");
  891. console.log(" --end [yyyy-mm-ddThh:mm:ss] - End time.");
  892. console.log(" --duration [minutes] - Duration of the share, default is 60 minutes.");
  893. console.log(" --daily - Add recurring daily device share.");
  894. console.log(" --weekly - Add recurring weekly device share.");
  895. console.log(" --port [portnumber] - Set alternative port for http or https, default is 80 for http and 443 for https.");
  896. break;
  897. }
  898. case 'agentdownload': {
  899. console.log("Download an agent of a specific type for a given device group, Example usages:\r\n");
  900. console.log(winRemoveSingleQuotes(" MeshCtrl AgentDownload --id 'groupid' --type 3"));
  901. console.log(winRemoveSingleQuotes(" MeshCtrl AgentDownload --id 'groupid' --type 3 --installflags 1"));
  902. console.log("\r\nRequired arguments:\r\n");
  903. console.log(" --type [ArchitectureNumber] - Agent architecture number.");
  904. if (process.platform == 'win32') {
  905. console.log(" --id [groupid] - The device group identifier.");
  906. } else {
  907. console.log(" --id '[groupid]' - The device group identifier.");
  908. }
  909. console.log("\r\nOptional arguments:\r\n");
  910. console.log(" --installflags [InstallFlagsNumber] - With the following choices:");
  911. console.log(" installflags 0 - Default, Interactive & Background, offers connect button & install/uninstall");
  912. console.log(" installflags 1 - Interactive only, offers only connect button, not install/uninstall");
  913. console.log(" installflags 2 - Background only, offers only install/uninstall, not connect");
  914. break;
  915. }
  916. case 'upload': {
  917. console.log("Upload a local file to a remote device, Example usages:\r\n");
  918. console.log(winRemoveSingleQuotes(" MeshCtrl Upload --id 'deviceid' --file sample.txt --target c:\\"));
  919. console.log(winRemoveSingleQuotes(" MeshCtrl Upload --id 'deviceid' --file sample.txt --target /tmp"));
  920. console.log("\r\nRequired arguments:\r\n");
  921. if (process.platform == 'win32') {
  922. console.log(" --id [deviceid] - The device identifier.");
  923. } else {
  924. console.log(" --id '[deviceid]' - The device identifier.");
  925. }
  926. console.log(" --file [localfile] - The local file to upload.");
  927. console.log(" --target [remotepath] - The remote path to upload the file to.");
  928. break;
  929. }
  930. case 'download': {
  931. console.log("Download a file from a remote device, Example usages:\r\n");
  932. console.log(winRemoveSingleQuotes(" MeshCtrl Download --id 'deviceid' --file C:\\sample.txt --target c:\\temp"));
  933. console.log(winRemoveSingleQuotes(" MeshCtrl Download --id 'deviceid' --file /tmp/sample.txt --target /tmp"));
  934. console.log("\r\nRequired arguments:\r\n");
  935. if (process.platform == 'win32') {
  936. console.log(" --id [deviceid] - The device identifier.");
  937. } else {
  938. console.log(" --id '[deviceid]' - The device identifier.");
  939. }
  940. console.log(" --file [remotefile] - The remote file to download.");
  941. console.log("\r\nOptional arguments:\r\n");
  942. console.log(" --target [localpath] - The local path to download the file to.");
  943. break;
  944. }
  945. case 'deviceopenurl': {
  946. console.log("Open a web page on a remote device, Example usages:\r\n");
  947. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceOpenUrl --id 'deviceid' --openurl http://meshcentral.com"));
  948. console.log("\r\nRequired arguments:\r\n");
  949. if (process.platform == 'win32') {
  950. console.log(" --id [deviceid] - The device identifier.");
  951. } else {
  952. console.log(" --id '[deviceid]' - The device identifier.");
  953. }
  954. console.log(" --openurl [url] - Link to the web page.");
  955. break;
  956. }
  957. case 'devicemessage': {
  958. console.log("Display a message on the remote device, Example usages:\r\n");
  959. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceMessage --id 'deviceid' --msg \"message\""));
  960. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceMessage --id 'deviceid' --msg \"message\" --title \"title\""));
  961. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceMessage --id 'deviceid' --msg \"message\" --title \"title\" --timeout 120000"));
  962. console.log("\r\nRequired arguments:\r\n");
  963. if (process.platform == 'win32') {
  964. console.log(" --id [deviceid] - The device identifier.");
  965. } else {
  966. console.log(" --id '[deviceid]' - The device identifier.");
  967. }
  968. console.log(" --msg [message] - The message to display.");
  969. console.log("\r\nOptional arguments:\r\n");
  970. console.log(" --title [title] - Messagebox title, default is \"MeshCentral\".");
  971. console.log(" --timeout [miliseconds] - After timeout messagebox vanishes, 0 keeps messagebox open until closed manually, default is 120000 (2 Minutes).");
  972. break;
  973. }
  974. case 'devicetoast': {
  975. console.log("Display a toast message on the remote device, Example usages:\r\n");
  976. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceToast --id 'deviceid' --msg \"message\""));
  977. console.log(winRemoveSingleQuotes(" MeshCtrl DeviceToast --id 'deviceid' --msg \"message\" --title \"title\""));
  978. console.log("\r\nRequired arguments:\r\n");
  979. if (process.platform == 'win32') {
  980. console.log(" --id [deviceid] - The device identifier.");
  981. } else {
  982. console.log(" --id '[deviceid]' - The device identifier.");
  983. }
  984. console.log(" --msg [message] - The message to display.");
  985. console.log("\r\nOptional arguments:\r\n");
  986. console.log(" --title [title] - Toast title, default is \"MeshCentral\".");
  987. break;
  988. }
  989. case 'groupmessage': {
  990. console.log("Open a message box on remote devices in a specific device group, Example usages:\r\n");
  991. console.log(winRemoveSingleQuotes(" MeshCtrl GroupMessage --id 'devicegroupid' --msg \"message\""));
  992. console.log(winRemoveSingleQuotes(" MeshCtrl GroupMessage --id 'devicegroupid' --msg \"message\" --title \"title\""));
  993. console.log(winRemoveSingleQuotes(" MeshCtrl GroupMessage --id 'devicegroupid' --msg \"message\" --title \"title\" --timeout 120000"));
  994. console.log("\r\nRequired arguments:\r\n");
  995. if (process.platform == 'win32') {
  996. console.log(" --id [devicegroupid] - The device identifier.");
  997. } else {
  998. console.log(" --id '[devicegroupid]' - The device identifier.");
  999. }
  1000. console.log(" --msg [message] - The message to display.");
  1001. console.log("\r\nOptional arguments:\r\n");
  1002. console.log(" --title [title] - Messagebox title, default is \"MeshCentral\".");
  1003. console.log(" --timeout [miliseconds] - After timeout messagebox vanishes, 0 keeps messagebox open until closed manually, default is 120000 (2 Minutes).");
  1004. break;
  1005. }
  1006. case 'grouptoast': {
  1007. console.log("Display a toast notification on remote devices in a specific device group, Example usages:\r\n");
  1008. console.log(winRemoveSingleQuotes(" MeshCtrl GroupToast --id 'devicegroupid' --msg \"message\""));
  1009. console.log(winRemoveSingleQuotes(" MeshCtrl GroupToast --id 'devicegroupid' --msg \"message\" --title \"title\""));
  1010. console.log("\r\nRequired arguments:\r\n");
  1011. if (process.platform == 'win32') {
  1012. console.log(" --id [devicegroupid] - The device identifier.");
  1013. } else {
  1014. console.log(" --id '[devicegroupid]' - The device identifier.");
  1015. }
  1016. console.log(" --msg [message] - The message to display.");
  1017. console.log("\r\nOptional arguments:\r\n");
  1018. console.log(" --title [title] - Toast title, default is \"MeshCentral\".");
  1019. break;
  1020. }
  1021. case 'report': {
  1022. console.log("Generate a CSV report, Example usages:\r\n");
  1023. console.log(" MeshCtrl Report --type sessions --devicegroup mesh//...");
  1024. console.log(" MeshCtrl Report --type traffic --json");
  1025. console.log(" MeshCtrl Report --type logins --groupby day");
  1026. console.log(" MeshCtrl Report --type db");
  1027. console.log("\r\nOptional arguments:\r\n");
  1028. console.log(" --start [yyyy-mm-ddThh:mm:ss] - Filter the results starting at that date. Defaults to last 24h and last week when used with --groupby day. Usable with sessions, traffic and logins");
  1029. console.log(" --end [yyyy-mm-ddThh:mm:ss] - Filter the results ending at that date. Defaults to now. Usable with sessions, traffic and logins");
  1030. console.log(" --groupby [name] - How to group results. Options: user, day, device. Defaults to user. User and day usable in sessions and logins, device usable in sessions.");
  1031. console.log(" --devicegroup [devicegroupid] - Filter the results by device group. Usable in sessions");
  1032. console.log(" --showtraffic - Add traffic data in sessions report");
  1033. break;
  1034. }
  1035. default: {
  1036. console.log("Get help on an action. Type:\r\n\r\n help [action]\r\n\r\nPossible actions are: " + possibleCommands.join(', ') + '.');
  1037. }
  1038. }
  1039. }
  1040. break;
  1041. }
  1042. }
  1043. if (ok) {
  1044. if(args.loginpass===true){
  1045. const readline = require('readline');
  1046. const rl = readline.createInterface({
  1047. input: process.stdin,
  1048. output: process.stdout,
  1049. terminal: false
  1050. });
  1051. process.stdout.write('Enter your password: ');
  1052. const stdin = process.openStdin();
  1053. stdin.setRawMode(true); // Set raw mode to prevent echoing of characters
  1054. stdin.resume();
  1055. args.loginpass = '';
  1056. process.stdin.on('data', (char) => {
  1057. char = char + '';
  1058. switch (char) {
  1059. case '\n':
  1060. case '\r':
  1061. case '\u0004': // They've finished entering their password
  1062. stdin.setRawMode(false);
  1063. stdin.pause();
  1064. process.stdout.clearLine(); process.stdout.cursorTo(0);
  1065. rl.close();
  1066. serverConnect();
  1067. break;
  1068. case '\u0003': // Ctrl+C
  1069. process.stdout.write('\n');
  1070. process.exit();
  1071. break;
  1072. default: // Mask the password with "*"
  1073. args.loginpass += char;
  1074. process.stdout.clearLine(); process.stdout.cursorTo(0);
  1075. process.stdout.write('Enter your password: ' + '*'.repeat(args.loginpass.length));
  1076. break;
  1077. }
  1078. });
  1079. }else{
  1080. serverConnect();
  1081. }
  1082. }
  1083. }
  1084. function displayConfigHelp() {
  1085. console.log("Perform operations on the config.json file. Example usage:\r\n");
  1086. console.log(" MeshCtrl config --show");
  1087. console.log("\r\nOptional arguments:\r\n");
  1088. console.log(" --show - Display the config.json file.");
  1089. console.log(" --listdomains - Display non-default domains.");
  1090. console.log(" --adddomain [domain] - Add a domain.");
  1091. console.log(" --removedomain [domain] - Remove a domain.");
  1092. console.log(" --settodomain [domain] - Set values to the domain.");
  1093. console.log(" --removefromdomain [domain] - Remove values from the domain.");
  1094. console.log("\r\nWith adddomain, removedomain, settodomain and removefromdomain you can add the key and value pair. For example:\r\n");
  1095. console.log(" --adddomain \"MyDomain\" --title \"My Server Name\" --newAccounts false");
  1096. console.log(" --settodomain \"MyDomain\" --title \"My Server Name\"");
  1097. console.log(" --removefromdomain \"MyDomain\" --title");
  1098. }
  1099. function performConfigOperations(args) {
  1100. var domainValues = ['title', 'title2', 'titlepicture', 'trustedcert', 'welcomepicture', 'welcometext', 'userquota', 'meshquota', 'newaccounts', 'usernameisemail', 'newaccountemaildomains', 'newaccountspass', 'newaccountsrights', 'geolocation', 'lockagentdownload', 'userconsentflags', 'Usersessionidletimeout', 'auth', 'ldapoptions', 'ldapusername', 'ldapuserbinarykey', 'ldapuseremail', 'footer', 'certurl', 'loginKey', 'userallowedip', 'agentallowedip', 'agentnoproxy', 'agentconfig', 'orphanagentuser', 'httpheaders', 'yubikey', 'passwordrequirements', 'limits', 'amtacmactivation', 'redirects', 'sessionrecording', 'hide'];
  1101. var domainObjectValues = ['ldapoptions', 'httpheaders', 'yubikey', 'passwordrequirements', 'limits', 'amtacmactivation', 'redirects', 'sessionrecording'];
  1102. var domainArrayValues = ['newaccountemaildomains', 'newaccountsrights', 'loginkey', 'agentconfig'];
  1103. var configChange = false;
  1104. var fs = require('fs');
  1105. var path = require('path');
  1106. var configFile = 'config.json';
  1107. var didSomething = 0;
  1108. if (fs.existsSync(configFile) == false) { configFile = path.join('meshcentral-data', 'config.json'); }
  1109. if (fs.existsSync(configFile) == false) { configFile = path.join(__dirname, 'config.json'); }
  1110. if (fs.existsSync(configFile) == false) { configFile = path.join(__dirname, 'meshcentral-data', 'config.json'); }
  1111. if (fs.existsSync(configFile) == false) { configFile = path.join(__dirname, '..', 'meshcentral-data', 'config.json'); }
  1112. if (fs.existsSync(configFile) == false) { configFile = path.join(__dirname, '..', '..', 'meshcentral-data', 'config.json'); }
  1113. if (fs.existsSync(configFile) == false) { console.log("Unable to find config.json."); return; }
  1114. var config = null;
  1115. try { config = fs.readFileSync(configFile).toString('utf8'); } catch (ex) { console.log("Error: Unable to read config.json"); return; }
  1116. try { config = JSON.parse(fs.readFileSync(configFile)); } catch (e) { console.log('ERROR: Unable to parse ' + configFile + '.'); return null; }
  1117. if (args.adddomain != null) {
  1118. didSomething++;
  1119. if (config.domains == null) { config.domains = {}; }
  1120. if (config.domains[args.adddomain] != null) { console.log("Error: Domain \"" + args.adddomain + "\" already exists"); }
  1121. else {
  1122. configChange = true;
  1123. config.domains[args.adddomain] = {};
  1124. for (var i in args) {
  1125. if (domainValues.indexOf(i.toLowerCase()) >= 0) {
  1126. if (args[i] == 'true') { args[i] = true; } else if (args[i] == 'false') { args[i] = false; } else if (parseInt(args[i]) == args[i]) { args[i] = parseInt(args[i]); }
  1127. config.domains[args.adddomain][i] = args[i];
  1128. configChange = true;
  1129. }
  1130. }
  1131. }
  1132. }
  1133. if (args.removedomain != null) {
  1134. didSomething++;
  1135. if (config.domains == null) { config.domains = {}; }
  1136. if (config.domains[args.removedomain] == null) { console.log("Error: Domain \"" + args.removedomain + "\" does not exist"); }
  1137. else { delete config.domains[args.removedomain]; configChange = true; }
  1138. }
  1139. if (args.settodomain != null) {
  1140. didSomething++;
  1141. if (config.domains == null) { config.domains = {}; }
  1142. if (args.settodomain == true) { args.settodomain = ''; }
  1143. if (config.domains[args.settodomain] == null) { console.log("Error: Domain \"" + args.settodomain + "\" does not exist"); }
  1144. else {
  1145. for (var i in args) {
  1146. if ((i == '_') || (i == 'settodomain')) continue;
  1147. if (domainValues.indexOf(i.toLowerCase()) >= 0) {
  1148. var isObj = (domainObjectValues.indexOf(i.toLowerCase()) >= 0);
  1149. var isArr = (domainArrayValues.indexOf(i.toLowerCase()) >= 0);
  1150. if ((isObj == false) && (isArr == false)) {
  1151. // Simple value set
  1152. if (args[i] == '') { delete config.domains[args.settodomain][i]; configChange = true; } else {
  1153. if (args[i] == 'true') { args[i] = true; } else if (args[i] == 'false') { args[i] = false; } else if (parseInt(args[i]) == args[i]) { args[i] = parseInt(args[i]); }
  1154. config.domains[args.settodomain][i] = args[i];
  1155. configChange = true;
  1156. }
  1157. } else if (isObj || isArr) {
  1158. // Set an object/array value
  1159. if (args[i] == '') { delete config.domains[args.settodomain][i]; configChange = true; } else {
  1160. var x = null;
  1161. try { x = JSON.parse(args[i]); } catch (ex) { }
  1162. if ((x == null) || (typeof x != 'object')) { console.log("Unable to parse JSON for " + i + "."); } else {
  1163. if (isArr && Array.isArray(x) == false) {
  1164. console.log("Value " + i + " must be an array.");
  1165. } else if (!isArr && Array.isArray(x) == true) {
  1166. console.log("Value " + i + " must be an object.");
  1167. } else {
  1168. config.domains[args.settodomain][i] = x;
  1169. configChange = true;
  1170. }
  1171. }
  1172. }
  1173. }
  1174. } else {
  1175. console.log('Invalid configuration value: ' + i);
  1176. }
  1177. }
  1178. }
  1179. }
  1180. if (args.removefromdomain != null) {
  1181. didSomething++;
  1182. if (config.domains == null) { config.domains = {}; }
  1183. if (config.domains[args.removefromdomain] == null) { console.log("Error: Domain \"" + args.removefromdomain + "\" does not exist"); }
  1184. else { for (var i in args) { if (domainValues.indexOf(i.toLowerCase()) >= 0) { delete config.domains[args.removefromdomain][i]; configChange = true; } } }
  1185. }
  1186. if (configChange) {
  1187. try { fs.writeFileSync(configFile, JSON.stringify(config, null, 2)); } catch (ex) { console.log("Error: Unable to read config.json"); return; }
  1188. }
  1189. if (args.show == 1) {
  1190. console.log(JSON.stringify(config, null, 2)); return;
  1191. } else if (args.listdomains == 1) {
  1192. if (config.domains == null) {
  1193. console.log('No domains found.'); return;
  1194. } else {
  1195. // Show the list of active domains, skip the default one.
  1196. for (var i in config.domains) { if ((i != '') && (i[0] != '_')) { console.log(i); } } return;
  1197. }
  1198. } else {
  1199. if (didSomething == 0) {
  1200. displayConfigHelp();
  1201. } else {
  1202. console.log("Done.");
  1203. }
  1204. }
  1205. }
  1206. function onVerifyServer(clientName, certs) { return null; }
  1207. function serverConnect() {
  1208. const WebSocket = require('ws');
  1209. var url = 'wss://localhost/control.ashx';
  1210. if (args.url) {
  1211. url = args.url;
  1212. if (url.length < 5) { console.log("Invalid url."); process.exit(); return; }
  1213. if ((url.startsWith('wss://') == false) && (url.startsWith('ws://') == false)) { console.log("Invalid url."); process.exit(); return; }
  1214. var i = url.indexOf('?key='), loginKey = null;
  1215. if (i >= 0) { loginKey = url.substring(i + 5); url = url.substring(0, i); }
  1216. if (url.endsWith('/') == false) { url += '/'; }
  1217. url += 'control.ashx';
  1218. if (loginKey != null) { url += '?key=' + loginKey; }
  1219. }
  1220. // TODO: checkServerIdentity does not work???
  1221. var options = { rejectUnauthorized: false, checkServerIdentity: onVerifyServer }
  1222. // Setup the HTTP proxy if needed
  1223. if (args.proxy != null) {
  1224. const HttpsProxyAgent = require('https-proxy-agent');
  1225. options.agent = new HttpsProxyAgent(require('url').parse(args.proxy));
  1226. }
  1227. // Password authentication
  1228. if (args.loginpass != null) {
  1229. var username = 'admin';
  1230. if (args.loginuser != null) { username = args.loginuser; }
  1231. var token = '';
  1232. if (args.token != null) { token = ',' + Buffer.from('' + args.token).toString('base64'); }
  1233. options.headers = { 'x-meshauth': Buffer.from('' + username).toString('base64') + ',' + Buffer.from('' + args.loginpass).toString('base64') + token }
  1234. }
  1235. // Cookie authentication
  1236. var ckey = null, loginCookie = null;
  1237. if (args.loginkey != null) {
  1238. // User key passed in as argument hex
  1239. if (args.loginkey.length != 160) { loginCookie = args.loginkey; }
  1240. ckey = Buffer.from(args.loginkey, 'hex');
  1241. if (ckey.length != 80) { ckey = null; loginCookie = args.loginkey; }
  1242. } else if (args.loginkeyfile != null) {
  1243. // Load key from hex file
  1244. var fs = require('fs');
  1245. try {
  1246. var keydata = fs.readFileSync(args.loginkeyfile, 'utf8').split(' ').join('').split('\r').join('').split('\n').join('');
  1247. ckey = Buffer.from(keydata, 'hex');
  1248. if (ckey.length != 80) { ckey = null; loginCookie = args.loginkey; }
  1249. } catch (ex) { console.log(ex.message); process.exit(); return; }
  1250. }
  1251. settings.xxurl = url;
  1252. if (ckey != null) {
  1253. var domainid = '', username = 'admin';
  1254. if (args.logindomain != null) { domainid = args.logindomain; }
  1255. if (args.loginuser != null) { username = args.loginuser; }
  1256. url += (url.indexOf('?key=') >= 0 ? '&auth=' : '?auth=') + encodeCookie({ userid: 'user/' + domainid + '/' + username, domainid: domainid }, ckey);
  1257. } else {
  1258. if (args.logindomain != null) { console.log("--logindomain can only be used along with --loginkey."); process.exit(); return; }
  1259. if (loginCookie != null) { url += (url.indexOf('?key=') >= 0 ? '&auth=' : '?auth=') + loginCookie; }
  1260. }
  1261. const ws = new WebSocket(url, options);
  1262. //console.log('Connecting to ' + url);
  1263. ws.on('open', function open() {
  1264. //console.log('Connected.');
  1265. switch (settings.cmd) {
  1266. case 'serverinfo': { break; }
  1267. case 'userinfo': { break; }
  1268. case 'listusers': { ws.send(JSON.stringify({ action: 'users', responseid: 'meshctrl' })); break; }
  1269. case 'listusersessions': { ws.send(JSON.stringify({ action: 'wssessioncount', responseid: 'meshctrl' })); break; }
  1270. case 'removeallusersfromusergroup':
  1271. case 'listusergroups': { ws.send(JSON.stringify({ action: 'usergroups', responseid: 'meshctrl' })); break; }
  1272. case 'listdevicegroups': { ws.send(JSON.stringify({ action: 'meshes', responseid: 'meshctrl' })); break; }
  1273. case 'listusersofdevicegroup': { ws.send(JSON.stringify({ action: 'meshes', responseid: 'meshctrl' })); break; }
  1274. case 'listdevices': {
  1275. if (args.details) {
  1276. // Get list of devices with lots of details
  1277. ws.send(JSON.stringify({ action: 'getDeviceDetails', type: (args.csv) ? 'csv' : 'json' }));
  1278. } else if (args.group) {
  1279. ws.send(JSON.stringify({ action: 'nodes', meshname: args.group, responseid: 'meshctrl' }));
  1280. } else if (args.id) {
  1281. ws.send(JSON.stringify({ action: 'nodes', meshid: args.id, responseid: 'meshctrl' }));
  1282. } else {
  1283. ws.send(JSON.stringify({ action: 'meshes' }));
  1284. ws.send(JSON.stringify({ action: 'nodes', responseid: 'meshctrl' }));
  1285. }
  1286. break;
  1287. }
  1288. case 'listevents': {
  1289. limit = null;
  1290. if (args.limit) { limit = parseInt(args.limit); }
  1291. if ((typeof limit != 'number') || (limit < 1)) { limit = null; }
  1292. var cmd = null;
  1293. if (args.userid) {
  1294. cmd = { action: 'events', user: args.userid, responseid: 'meshctrl' };
  1295. } else if (args.id) {
  1296. cmd = { action: 'events', nodeid: args.id, responseid: 'meshctrl' };
  1297. } else {
  1298. cmd = { action: 'events', responseid: 'meshctrl' };
  1299. }
  1300. if (typeof limit == 'number') { cmd.limit = limit; }
  1301. ws.send(JSON.stringify(cmd));
  1302. break;
  1303. }
  1304. case 'logintokens': {
  1305. if (args.add) {
  1306. var cmd = { action: 'createLoginToken', name: args.add, expire: 0, responseid: 'meshctrl' };
  1307. if (args.expire) { cmd.expire = parseInt(args.expire); }
  1308. ws.send(JSON.stringify(cmd));
  1309. } else {
  1310. var cmd = { action: 'loginTokens', responseid: 'meshctrl' };
  1311. if (args.remove) { cmd.remove = [args.remove]; }
  1312. ws.send(JSON.stringify(cmd));
  1313. }
  1314. break;
  1315. }
  1316. case 'adduser': {
  1317. var siteadmin = getSiteAdminRights(args);
  1318. if (args.randompass) { args.pass = getRandomAmtPassword(); }
  1319. var op = { action: 'adduser', username: args.user, pass: args.pass, responseid: 'meshctrl' };
  1320. if (args.email) { op.email = args.email; if (args.emailverified) { op.emailVerified = true; } }
  1321. if (args.resetpass) { op.resetNextLogin = true; }
  1322. if (siteadmin != -1) { op.siteadmin = siteadmin; }
  1323. if (args.domain) { op.domain = args.domain; }
  1324. if (args.phone === true) { op.phone = ''; }
  1325. if (typeof args.phone == 'string') { op.phone = args.phone; }
  1326. if (typeof args.realname == 'string') { op.realname = args.realname; }
  1327. ws.send(JSON.stringify(op));
  1328. break;
  1329. }
  1330. case 'edituser': {
  1331. var userid = args.userid;
  1332. if ((args.domain != null) && (userid.indexOf('/') < 0)) { userid = 'user/' + args.domain + '/' + userid; }
  1333. var siteadmin = getSiteAdminRights(args);
  1334. var op = { action: 'edituser', userid: userid, responseid: 'meshctrl' };
  1335. if (args.email) { op.email = args.email; if (args.emailverified) { op.emailVerified = true; } }
  1336. if (args.resetpass) { op.resetNextLogin = true; }
  1337. if (siteadmin != -1) { op.siteadmin = siteadmin; }
  1338. if (args.domain) { op.domain = args.domain; }
  1339. if (args.phone === true) { op.phone = ''; }
  1340. if (typeof args.phone == 'string') { op.phone = args.phone; }
  1341. if (typeof args.realname == 'string') { op.realname = args.realname; }
  1342. if (args.realname === true) { op.realname = ''; }
  1343. ws.send(JSON.stringify(op));
  1344. break;
  1345. }
  1346. case 'removeuser': {
  1347. var userid = args.userid;
  1348. if ((args.domain != null) && (userid.indexOf('/') < 0)) { userid = 'user/' + args.domain + '/' + userid; }
  1349. ws.send(JSON.stringify({ action: 'deleteuser', userid: userid, responseid: 'meshctrl' }));
  1350. break;
  1351. }
  1352. case 'addusergroup': {
  1353. var op = { action: 'createusergroup', name: args.name, desc: args.desc, responseid: 'meshctrl' };
  1354. if (args.domain) { op.domain = args.domain; }
  1355. ws.send(JSON.stringify(op));
  1356. break;
  1357. }
  1358. case 'removeusergroup': {
  1359. var ugrpid = args.groupid;
  1360. if ((args.domain != null) && (userid.indexOf('/') < 0)) { ugrpid = 'ugrp/' + args.domain + '/' + ugrpid; }
  1361. ws.send(JSON.stringify({ action: 'deleteusergroup', ugrpid: ugrpid, responseid: 'meshctrl' }));
  1362. break;
  1363. }
  1364. case 'addtousergroup': {
  1365. var ugrpid = args.groupid;
  1366. if ((args.domain != null) && (userid.indexOf('/') < 0)) { ugrpid = 'ugrp/' + args.domain + '/' + ugrpid; }
  1367. // Add a user to a user group
  1368. if (args.userid != null) {
  1369. var userid = args.userid;
  1370. if ((args.domain != null) && (userid.indexOf('/') < 0)) { userid = 'user/' + args.domain + '/' + userid; }
  1371. ws.send(JSON.stringify({ action: 'addusertousergroup', ugrpid: ugrpid, usernames: [userid.split('/')[2]], responseid: 'meshctrl' }));
  1372. break;
  1373. }
  1374. if ((args.id != null) && (args.id.startsWith('user/'))) {
  1375. ws.send(JSON.stringify({ action: 'addusertousergroup', ugrpid: ugrpid, usernames: [args.id.split('/')[2]], responseid: 'meshctrl' }));
  1376. break;
  1377. }
  1378. var rights = 0;
  1379. if (args.rights != null) { rights = parseInt(args.rights); }
  1380. // Add a device group to a user group
  1381. if (args.meshid != null) {
  1382. var meshid = args.meshid;
  1383. if ((args.domain != null) && (userid.indexOf('/') < 0)) { meshid = 'mesh/' + args.domain + '/' + meshid; }
  1384. ws.send(JSON.stringify({ action: 'addmeshuser', meshid: meshid, userid: ugrpid, meshadmin: rights, responseid: 'meshctrl' }));
  1385. break;
  1386. }
  1387. if ((args.id != null) && (args.id.startsWith('mesh/'))) {
  1388. ws.send(JSON.stringify({ action: 'addmeshuser', meshid: args.id, userid: ugrpid, meshadmin: rights, responseid: 'meshctrl' }));
  1389. break;
  1390. }
  1391. // Add a device to a user group
  1392. if (args.nodeid != null) {
  1393. var nodeid = args.nodeid;
  1394. if ((args.domain != null) && (userid.indexOf('/') < 0)) { nodeid = 'node/' + args.domain + '/' + nodeid; }
  1395. ws.send(JSON.stringify({ action: 'adddeviceuser', nodeid: nodeid, userids: [ugrpid], rights: rights, responseid: 'meshctrl' }));
  1396. break;
  1397. }
  1398. if ((args.id != null) && (args.id.startsWith('node/'))) {
  1399. ws.send(JSON.stringify({ action: 'adddeviceuser', nodeid: args.id, userids: [ugrpid], rights: rights, responseid: 'meshctrl' }));
  1400. break;
  1401. }
  1402. break;
  1403. }
  1404. case 'removefromusergroup': {
  1405. var ugrpid = args.groupid;
  1406. if ((args.domain != null) && (userid.indexOf('/') < 0)) { ugrpid = 'ugrp/' + args.domain + '/' + ugrpid; }
  1407. // Remove a user from a user group
  1408. if (args.userid != null) {
  1409. var userid = args.userid;
  1410. if ((args.domain != null) && (userid.indexOf('/') < 0)) { userid = 'user/' + args.domain + '/' + userid; }
  1411. ws.send(JSON.stringify({ action: 'removeuserfromusergroup', ugrpid: ugrpid, userid: userid, responseid: 'meshctrl' }));
  1412. break;
  1413. }
  1414. if ((args.id != null) && (args.id.startsWith('user/'))) {
  1415. ws.send(JSON.stringify({ action: 'removeuserfromusergroup', ugrpid: ugrpid, userid: args.id, responseid: 'meshctrl' }));
  1416. break;
  1417. }
  1418. // Remove a device group from a user group
  1419. if (args.meshid != null) {
  1420. var meshid = args.meshid;
  1421. if ((args.domain != null) && (userid.indexOf('/') < 0)) { meshid = 'mesh/' + args.domain + '/' + meshid; }
  1422. ws.send(JSON.stringify({ action: 'removemeshuser', meshid: meshid, userid: ugrpid, responseid: 'meshctrl' }));
  1423. break;
  1424. }
  1425. if ((args.id != null) && (args.id.startsWith('mesh/'))) {
  1426. ws.send(JSON.stringify({ action: 'removemeshuser', meshid: args.id, userid: ugrpid, responseid: 'meshctrl' }));
  1427. break;
  1428. }
  1429. // Remove a device from a user group
  1430. if (args.nodeid != null) {
  1431. var nodeid = args.nodeid;
  1432. if ((args.domain != null) && (userid.indexOf('/') < 0)) { nodeid = 'node/' + args.domain + '/' + nodeid; }
  1433. ws.send(JSON.stringify({ action: 'adddeviceuser', nodeid: nodeid, userids: [ugrpid], rights: 0, responseid: 'meshctrl', remove: true }));
  1434. break;
  1435. }
  1436. if ((args.id != null) && (args.id.startsWith('node/'))) {
  1437. ws.send(JSON.stringify({ action: 'adddeviceuser', nodeid: args.id, userids: [ugrpid], rights: 0, responseid: 'meshctrl', remove: true }));
  1438. break;
  1439. }
  1440. break;
  1441. }
  1442. case 'adddevicegroup': {
  1443. var op = { action: 'createmesh', meshname: args.name, meshtype: 2, responseid: 'meshctrl' };
  1444. if (args.desc) { op.desc = args.desc; }
  1445. if (args.amtonly) { op.meshtype = 1; }
  1446. if (args.agentless) { op.meshtype = 3; }
  1447. if (args.features) { op.flags = parseInt(args.features); }
  1448. if (args.consent) { op.consent = parseInt(args.consent); }
  1449. ws.send(JSON.stringify(op));
  1450. break;
  1451. }
  1452. case 'removedevicegroup': {
  1453. var op = { action: 'deletemesh', responseid: 'meshctrl' };
  1454. if (args.id) { op.meshid = args.id; } else if (args.group) { op.meshname = args.group; }
  1455. ws.send(JSON.stringify(op));
  1456. break;
  1457. }
  1458. case 'editdevicegroup': {
  1459. var op = { action: 'editmesh', responseid: 'meshctrl' };
  1460. if (args.id) { op.meshid = args.id; } else if (args.group) { op.meshidname = args.group; }
  1461. if ((typeof args.name == 'string') && (args.name != '')) { op.meshname = args.name; }
  1462. if (args.desc === true) { op.desc = ""; } else if (typeof args.desc == 'string') { op.desc = args.desc; }
  1463. if (args.invitecodes === true) { op.invite = "*"; } else if (typeof args.invitecodes == 'string') {
  1464. var invitecodes = args.invitecodes.split(','), invitecodes2 = [];
  1465. for (var i in invitecodes) { if (invitecodes[i].length > 0) { invitecodes2.push(invitecodes[i]); } }
  1466. if (invitecodes2.length > 0) {
  1467. op.invite = { codes: invitecodes2, flags: 0 };
  1468. if (args.backgroundonly === true) { op.invite.flags = 2; }
  1469. else if (args.interactiveonly === true) { op.invite.flags = 1; }
  1470. }
  1471. }
  1472. if (args.flags != null) {
  1473. var flags = parseInt(args.flags);
  1474. if (typeof flags == 'number') { op.flags = flags; }
  1475. }
  1476. if (args.consent != null) {
  1477. var consent = parseInt(args.consent);
  1478. if (typeof consent == 'number') { op.consent = consent; }
  1479. }
  1480. ws.send(JSON.stringify(op));
  1481. break;
  1482. }
  1483. case 'movetodevicegroup': {
  1484. var op = { action: 'changeDeviceMesh', responseid: 'meshctrl', nodeids: [args.devid] };
  1485. if (args.id) { op.meshid = args.id; } else if (args.group) { op.meshname = args.group; }
  1486. ws.send(JSON.stringify(op));
  1487. break;
  1488. }
  1489. case 'addusertodevicegroup': {
  1490. var meshrights = 0;
  1491. if (args.fullrights) { meshrights = 0xFFFFFFFF; }
  1492. if (args.editgroup) { meshrights |= 1; }
  1493. if (args.manageusers) { meshrights |= 2; }
  1494. if (args.managedevices) { meshrights |= 4; }
  1495. if (args.remotecontrol) { meshrights |= 8; }
  1496. if (args.agentconsole) { meshrights |= 16; }
  1497. if (args.serverfiles) { meshrights |= 32; }
  1498. if (args.wakedevices) { meshrights |= 64; }
  1499. if (args.notes) { meshrights |= 128; }
  1500. if (args.desktopviewonly) { meshrights |= 256; }
  1501. if (args.noterminal) { meshrights |= 512; }
  1502. if (args.nofiles) { meshrights |= 1024; }
  1503. if (args.noamt) { meshrights |= 2048; }
  1504. if (args.limiteddesktop) { meshrights |= 4096; }
  1505. if (args.limitedevents) { meshrights |= 8192; }
  1506. if (args.chatnotify) { meshrights |= 16384; }
  1507. if (args.uninstall) { meshrights |= 32768; }
  1508. var op = { action: 'addmeshuser', usernames: [args.userid], meshadmin: meshrights, responseid: 'meshctrl' };
  1509. if (args.id) { op.meshid = args.id; } else if (args.group) { op.meshname = args.group; }
  1510. ws.send(JSON.stringify(op));
  1511. break;
  1512. }
  1513. case 'removeuserfromdevicegroup': {
  1514. var op = { action: 'removemeshuser', userid: args.userid, responseid: 'meshctrl' };
  1515. if (args.id) { op.meshid = args.id; } else if (args.group) { op.meshname = args.group; }
  1516. ws.send(JSON.stringify(op));
  1517. break;
  1518. }
  1519. case 'addusertodevice': {
  1520. var meshrights = 0;
  1521. if (args.fullrights) { meshrights = (8 + 16 + 32 + 64 + 128 + 16384 + 32768); }
  1522. if (args.remotecontrol) { meshrights |= 8; }
  1523. if (args.agentconsole) { meshrights |= 16; }
  1524. if (args.serverfiles) { meshrights |= 32; }
  1525. if (args.wakedevices) { meshrights |= 64; }
  1526. if (args.notes) { meshrights |= 128; }
  1527. if (args.desktopviewonly) { meshrights |= 256; }
  1528. if (args.noterminal) { meshrights |= 512; }
  1529. if (args.nofiles) { meshrights |= 1024; }
  1530. if (args.noamt) { meshrights |= 2048; }
  1531. if (args.limiteddesktop) { meshrights |= 4096; }
  1532. if (args.limitedevents) { meshrights |= 8192; }
  1533. if (args.chatnotify) { meshrights |= 16384; }
  1534. if (args.uninstall) { meshrights |= 32768; }
  1535. var op = { action: 'adddeviceuser', nodeid: args.id, usernames: [args.userid], rights: meshrights, responseid: 'meshctrl' };
  1536. ws.send(JSON.stringify(op));
  1537. break;
  1538. }
  1539. case 'removeuserfromdevice': {
  1540. var op = { action: 'adddeviceuser', nodeid: args.id, usernames: [args.userid], rights: 0, remove: true, responseid: 'meshctrl' };
  1541. ws.send(JSON.stringify(op));
  1542. break;
  1543. }
  1544. case 'sendinviteemail': {
  1545. var op = { action: 'inviteAgent', email: args.email, name: '', os: '0', responseid: 'meshctrl' }
  1546. if (args.id) { op.meshid = args.id; } else if (args.group) { op.meshname = args.group; }
  1547. if (args.name) { op.name = args.name; }
  1548. if (args.message) { op.msg = args.message; }
  1549. ws.send(JSON.stringify(op));
  1550. break;
  1551. }
  1552. case 'generateinvitelink': {
  1553. var op = { action: 'createInviteLink', expire: args.hours, flags: 0, responseid: 'meshctrl' }
  1554. if (args.id) { op.meshid = args.id; } else if (args.group) { op.meshname = args.group; }
  1555. if (args.flags) { op.flags = args.flags; }
  1556. ws.send(JSON.stringify(op));
  1557. break;
  1558. }
  1559. case 'broadcast': {
  1560. var op = { action: 'userbroadcast', msg: args.msg, responseid: 'meshctrl' };
  1561. if (args.user) { op.userid = args.user; }
  1562. ws.send(JSON.stringify(op));
  1563. break;
  1564. }
  1565. case 'showevents': {
  1566. console.log('Connected. Press ctrl-c to end.');
  1567. break;
  1568. }
  1569. case 'deviceinfo': {
  1570. settings.deviceinfocount = 4;
  1571. ws.send(JSON.stringify({ action: 'nodes' }));
  1572. ws.send(JSON.stringify({ action: 'getnetworkinfo', nodeid: args.id, responseid: 'meshctrl' }));
  1573. ws.send(JSON.stringify({ action: 'lastconnect', nodeid: args.id, responseid: 'meshctrl' }));
  1574. ws.send(JSON.stringify({ action: 'getsysinfo', nodeid: args.id, nodeinfo: true, responseid: 'meshctrl' }));
  1575. break;
  1576. }
  1577. case 'removedevice': {
  1578. var op = { action: 'removedevices', nodeids: [ args.id ], responseid: 'meshctrl' };
  1579. ws.send(JSON.stringify(op));
  1580. break;
  1581. }
  1582. case 'editdevice': {
  1583. var op = { action: 'changedevice', nodeid: args.id, responseid: 'meshctrl' };
  1584. if (typeof args.name == 'string') { op.name = args.name; }
  1585. if (typeof args.name == 'number') { op.name = '' + args.name; }
  1586. if (args.desc) { if (args.desc === true) { op.desc = ''; } else if (typeof args.desc == 'string') { op.desc = args.desc; } else if (typeof args.desc == 'number') { op.desc = '' + args.desc; } }
  1587. if (args.tags) { if (args.tags === true) { op.tags = ''; } else if (typeof args.tags == 'string') { op.tags = args.tags.split(','); } else if (typeof args.tags == 'number') { op.tags = '' + args.tags; } }
  1588. if (args.icon) { op.icon = parseInt(args.icon); if ((typeof op.icon != 'number') || isNaN(op.icon) || (op.icon < 1) || (op.icon > 8)) { console.log("Icon must be between 1 and 8."); process.exit(1); return; } }
  1589. if (args.consent) { op.consent = parseInt(args.consent); if ((typeof op.consent != 'number') || isNaN(op.consent) || (op.consent < 1)) { console.log("Invalid consent flags."); process.exit(1); return; } }
  1590. ws.send(JSON.stringify(op));
  1591. break;
  1592. }
  1593. case 'runcommand': {
  1594. var runAsUser = 0;
  1595. if (args.runasuser) { runAsUser = 1; } else if (args.runasuseronly) { runAsUser = 2; }
  1596. var reply = false;
  1597. if (args.reply) { reply = true; }
  1598. ws.send(JSON.stringify({ action: 'runcommands', nodeids: [args.id], type: ((args.powershell) ? 2 : 0), cmds: args.run, responseid: 'meshctrl', runAsUser: runAsUser, reply: reply }));
  1599. break;
  1600. }
  1601. case 'shell':
  1602. case 'upload':
  1603. case 'download': {
  1604. ws.send("{\"action\":\"authcookie\"}");
  1605. break;
  1606. }
  1607. case 'devicepower': {
  1608. var nodes = args.id.split(',');
  1609. if (args.wake) {
  1610. // Wake operation
  1611. ws.send(JSON.stringify({ action: 'wakedevices', nodeids: nodes, responseid: 'meshctrl' }));
  1612. } else if (args.off) {
  1613. // Power off operation
  1614. ws.send(JSON.stringify({ action: 'poweraction', nodeids: nodes, actiontype: 2, responseid: 'meshctrl' }));
  1615. } else if (args.reset) {
  1616. // Reset operation
  1617. ws.send(JSON.stringify({ action: 'poweraction', nodeids: nodes, actiontype: 3, responseid: 'meshctrl' }));
  1618. } else if (args.sleep) {
  1619. // Sleep operation
  1620. ws.send(JSON.stringify({ action: 'poweraction', nodeids: nodes, actiontype: 4, responseid: 'meshctrl' }));
  1621. } else if (args.amton) {
  1622. // Intel AMT Power on operation
  1623. ws.send(JSON.stringify({ action: 'poweraction', nodeids: nodes, actiontype: 302, responseid: 'meshctrl' }));
  1624. } else if (args.amtoff) {
  1625. // Intel AMT Power off operation
  1626. ws.send(JSON.stringify({ action: 'poweraction', nodeids: nodes, actiontype: 308, responseid: 'meshctrl' }));
  1627. } else if (args.amtreset) {
  1628. // Intel AMT Power reset operation
  1629. ws.send(JSON.stringify({ action: 'poweraction', nodeids: nodes, actiontype: 310, responseid: 'meshctrl' }));
  1630. } else {
  1631. console.log('No power operation specified.');
  1632. process.exit(1);
  1633. }
  1634. break;
  1635. }
  1636. case 'agentdownload': {
  1637. // Download an agent
  1638. var u = settings.xxurl.replace('wss://', 'https://').replace('/control.ashx', '/meshagents');
  1639. if (u.indexOf('?') > 0) { u += '&'; } else { u += '?'; }
  1640. u += 'id=' + args.type + '&meshid=' + args.id;
  1641. if (args.installflags) {
  1642. if ((typeof parseInt(args.installflags) != 'number') || isNaN(parseInt(args.installflags)) || (parseInt(args.installflags) < 0) || (parseInt(args.installflags) > 2)) { console.log("Invalid Installflags."); process.exit(1); return; }
  1643. u += '&installflags=' + args.installflags;
  1644. }
  1645. const options = { rejectUnauthorized: false, checkServerIdentity: onVerifyServer }
  1646. const fs = require('fs');
  1647. const https = require('https');
  1648. var downloadSize = 0;
  1649. const req = https.request(u, options, function (res) {
  1650. if (res.statusCode != 200) {
  1651. console.log('Download error, statusCode: ' + res.statusCode);
  1652. process.exit(1);
  1653. } else {
  1654. // Agent the agent filename
  1655. var agentFileName = 'meshagent';
  1656. if ((res.headers) && (res.headers['content-disposition'] != null)) {
  1657. var i = res.headers['content-disposition'].indexOf('filename=\"');
  1658. if (i >= 0) {
  1659. agentFileName = res.headers['content-disposition'].substring(i + 10);
  1660. i = agentFileName.indexOf('\"');
  1661. if (i >= 0) { agentFileName = agentFileName.substring(0, i); }
  1662. }
  1663. }
  1664. // Check if this file already exists
  1665. if (fs.existsSync(agentFileName)) { console.log('File \"' + agentFileName + '\" already exists.'); process.exit(1); }
  1666. var fd = fs.openSync(agentFileName, 'w'); // Open the file for writing
  1667. res.on('data', function (d) {
  1668. downloadSize += d.length;
  1669. fs.writeSync(fd, d); // Save to file
  1670. });
  1671. res.on('end', function (d) {
  1672. fs.closeSync(fd); // Close file
  1673. console.log('Downloaded ' + downloadSize + ' byte(s) to \"' + agentFileName + '\"');
  1674. process.exit(1);
  1675. });
  1676. }
  1677. })
  1678. req.on('error', function (error) { console.error(error); process.exit(1); })
  1679. req.end()
  1680. break;
  1681. }
  1682. case 'devicesharing': {
  1683. if (args.add) {
  1684. if (args.add.length == 0) { console.log("Invalid guest name."); process.exit(1); }
  1685. // Sharing type, desktop or terminal
  1686. var p = 0;
  1687. if (args.type != null) {
  1688. var shareTypes = args.type.toLowerCase().split(',');
  1689. for (var i in shareTypes) { if ((shareTypes[i] != 'terminal') && (shareTypes[i] != 'desktop') && (shareTypes[i] != 'files') && (shareTypes[i] != 'http') && (shareTypes[i] != 'https')) { console.log("Unknown sharing type: " + shareTypes[i]); process.exit(1); } }
  1690. if (shareTypes.indexOf('terminal') >= 0) { p |= 1; }
  1691. if (shareTypes.indexOf('desktop') >= 0) { p |= 2; }
  1692. if (shareTypes.indexOf('files') >= 0) { p |= 4; }
  1693. if (shareTypes.indexOf('http') >= 0) { p |= 8; }
  1694. if (shareTypes.indexOf('https') >= 0) { p |= 16; }
  1695. }
  1696. if (p == 0) { p = 2; } // Desktop
  1697. // Sharing view only
  1698. var viewOnly = false;
  1699. if (args.viewonly) { viewOnly = true; }
  1700. // User consent
  1701. var consent = 0;
  1702. if (args.consent == null) {
  1703. if ((p & 1) != 0) { consent = 0x0002; } // Terminal notify
  1704. if ((p & 2) != 0) { consent = 0x0001; } // Desktop notify
  1705. if ((p & 4) != 0) { consent = 0x0004; } // Files notify
  1706. } else {
  1707. if (typeof args.consent == 'string') {
  1708. var flagStrs = args.consent.split(',');
  1709. for (var i in flagStrs) {
  1710. var flagStr = flagStrs[i].toLowerCase();
  1711. if (flagStr == 'none') { consent = 0; }
  1712. else if (flagStr == 'notify') {
  1713. if ((p & 1) != 0) { consent |= 0x0002; } // Terminal notify
  1714. if ((p & 2) != 0) { consent |= 0x0001; } // Desktop notify
  1715. if ((p & 4) != 0) { consent |= 0x0004; } // Files notify
  1716. } else if (flagStr == 'prompt') {
  1717. if ((p & 1) != 0) { consent |= 0x0010; } // Terminal prompt
  1718. if ((p & 2) != 0) { consent |= 0x0008; } // Desktop prompt
  1719. if ((p & 4) != 0) { consent |= 0x0020; } // Files prompt
  1720. } else if (flagStr == 'bar') {
  1721. if ((p & 2) != 0) { consent |= 0x0040; } // Desktop toolbar
  1722. } else { console.log("Unknown consent type."); process.exit(1); return; }
  1723. }
  1724. }
  1725. }
  1726. var port = null;
  1727. // Set Port Number if http or https
  1728. if ((p & 8) || (p & 16)) {
  1729. if (typeof args.port == 'number') {
  1730. if ((args.port < 1) || (args.port > 65535)) { console.log("Port number must be between 1 and 65535."); process.exit(1); }
  1731. port = args.port;
  1732. } else if ((p & 8)) {
  1733. port = 80;
  1734. } else if ((p & 16)) {
  1735. port = 443;
  1736. }
  1737. }
  1738. // Start and end time
  1739. var start = null, end = null;
  1740. if (args.start) { start = Math.floor(Date.parse(args.start) / 1000); end = start + (60 * 60); }
  1741. if (args.end) { if (start == null) { start = Math.floor(Date.now() / 1000) } end = Math.floor(Date.parse(args.end) / 1000); if (end <= start) { console.log("End time must be ahead of start time."); process.exit(1); return; } }
  1742. if (args.duration) { if (start == null) { start = Math.floor(Date.now() / 1000) } end = start + parseInt(args.duration * 60); }
  1743. // Recurring
  1744. var recurring = 0;
  1745. if (args.daily) { recurring = 1; } else if (args.weekly) { recurring = 2; }
  1746. if (recurring > 0) {
  1747. if (args.end != null) { console.log("End time can't be specified for recurring shares, use --duration only."); process.exit(1); return; }
  1748. if (args.duration == null) { args.duration = 60; } else { args.duration = parseInt(args.duration); }
  1749. if (start == null) { start = Math.floor(Date.now() / 1000) }
  1750. if ((typeof args.duration != 'number') || (args.duration < 1)) { console.log("Invalid duration value."); process.exit(1); return; }
  1751. // Recurring sharing
  1752. ws.send(JSON.stringify({ action: 'createDeviceShareLink', nodeid: args.id, guestname: args.add, p: p, consent: consent, start: start, expire: args.duration, recurring: recurring, viewOnly: viewOnly, port: port, responseid: 'meshctrl' }));
  1753. } else {
  1754. if ((start == null) && (end == null)) {
  1755. // Unlimited sharing
  1756. ws.send(JSON.stringify({ action: 'createDeviceShareLink', nodeid: args.id, guestname: args.add, p: p, consent: consent, expire: 0, viewOnly: viewOnly, port: port, responseid: 'meshctrl' }));
  1757. } else {
  1758. // Time limited sharing
  1759. ws.send(JSON.stringify({ action: 'createDeviceShareLink', nodeid: args.id, guestname: args.add, p: p, consent: consent, start: start, end: end, viewOnly: viewOnly, port: port, responseid: 'meshctrl' }));
  1760. }
  1761. }
  1762. } else if (args.remove) {
  1763. ws.send(JSON.stringify({ action: 'removeDeviceShare', nodeid: args.id, publicid: args.remove, responseid: 'meshctrl' }));
  1764. } else {
  1765. ws.send(JSON.stringify({ action: 'deviceShares', nodeid: args.id, responseid: 'meshctrl' }));
  1766. }
  1767. break;
  1768. }
  1769. case 'deviceopenurl': {
  1770. ws.send(JSON.stringify({ action: 'msg', type: 'openUrl', nodeid: args.id, url: args.openurl, responseid: 'meshctrl' }));
  1771. break;
  1772. }
  1773. case 'devicemessage': {
  1774. ws.send(JSON.stringify({ action: 'msg', type: 'messagebox', nodeid: args.id, title: args.title ? args.title : "MeshCentral", msg: args.msg, timeout: args.timeout ? args.timeout : 120000, responseid: 'meshctrl' }));
  1775. break;
  1776. }
  1777. case 'devicetoast': {
  1778. ws.send(JSON.stringify({ action: 'toast', nodeids: [args.id], title: args.title ? args.title : "MeshCentral", msg: args.msg, responseid: 'meshctrl' }));
  1779. break;
  1780. }
  1781. case 'groupmessage': {
  1782. ws.send(JSON.stringify({ action: 'nodes', meshid: args.id, responseid: 'meshctrl' }));
  1783. break;
  1784. }
  1785. case 'grouptoast': {
  1786. ws.send(JSON.stringify({ action: 'nodes', meshid: args.id, responseid: 'meshctrl' }));
  1787. break;
  1788. }
  1789. case 'report': {
  1790. var reporttype = 1;
  1791. switch(args.type) {
  1792. case 'traffic':
  1793. reporttype = 2;
  1794. break;
  1795. case 'logins':
  1796. reporttype = 3;
  1797. break;
  1798. case 'db':
  1799. reporttype = 4;
  1800. break;
  1801. }
  1802. var reportgroupby = 1;
  1803. if(args.groupby){
  1804. reportgroupby = args.groupby === 'device' ? 2 : args.groupby === 'day' ? 3: 1;
  1805. }
  1806. var start = null, end = null;
  1807. if (args.start) {
  1808. start = Math.floor(Date.parse(args.start) / 1000);
  1809. } else {
  1810. start = reportgroupby === 3 ? Math.round(new Date().getTime() / 1000) - (168 * 3600) : Math.round(new Date().getTime() / 1000) - (24 * 3600);
  1811. }
  1812. if (args.end) {
  1813. end = Math.floor(Date.parse(args.end) / 1000);
  1814. } else {
  1815. end = Math.round(new Date().getTime() / 1000);
  1816. }
  1817. if (end <= start) { console.log("End time must be ahead of start time."); process.exit(1); return; }
  1818. ws.send(JSON.stringify({ action: 'report', type: reporttype, groupBy: reportgroupby, devGroup: args.devicegroup || null, start, end, tz: Intl.DateTimeFormat().resolvedOptions().timeZone, tf: new Date().getTimezoneOffset(), showTraffic: args.hasOwnProperty('showtraffic'), l: 'en', responseid: 'meshctrl' }));
  1819. break;
  1820. }
  1821. }
  1822. });
  1823. function getSiteAdminRights(args) {
  1824. var siteadmin = -1;
  1825. if (typeof args.rights == 'number') {
  1826. siteadmin = args.rights;
  1827. } else if (typeof args.rights == 'string') {
  1828. siteadmin = 0;
  1829. var srights = args.rights.toLowerCase().split(',');
  1830. if (srights.indexOf('full') != -1) { siteadmin = 0xFFFFFFFF; }
  1831. if (srights.indexOf('none') != -1) { siteadmin = 0x00000000; }
  1832. if (srights.indexOf('backup') != -1 || srights.indexOf('serverbackup') != -1) { siteadmin |= 0x00000001; }
  1833. if (srights.indexOf('manageusers') != -1) { siteadmin |= 0x00000002; }
  1834. if (srights.indexOf('restore') != -1 || srights.indexOf('serverrestore') != -1) { siteadmin |= 0x00000004; }
  1835. if (srights.indexOf('fileaccess') != -1) { siteadmin |= 0x00000008; }
  1836. if (srights.indexOf('update') != -1 || srights.indexOf('serverupdate') != -1) { siteadmin |= 0x00000010; }
  1837. if (srights.indexOf('locked') != -1) { siteadmin |= 0x00000020; }
  1838. if (srights.indexOf('nonewgroups') != -1) { siteadmin |= 0x00000040; }
  1839. if (srights.indexOf('notools') != -1) { siteadmin |= 0x00000080; }
  1840. if (srights.indexOf('usergroups') != -1) { siteadmin |= 0x00000100; }
  1841. if (srights.indexOf('recordings') != -1) { siteadmin |= 0x00000200; }
  1842. if (srights.indexOf('locksettings') != -1) { siteadmin |= 0x00000400; }
  1843. if (srights.indexOf('allevents') != -1) { siteadmin |= 0x00000800; }
  1844. if (srights.indexOf('nonewdevices') != -1) { siteadmin |= 0x00001000; }
  1845. }
  1846. if (args.siteadmin) { siteadmin = 0xFFFFFFFF; }
  1847. if (args.manageusers) { if (siteadmin == -1) { siteadmin = 0; } siteadmin |= 2; }
  1848. if (args.fileaccess) { if (siteadmin == -1) { siteadmin = 0; } siteadmin |= 8; }
  1849. if (args.serverupdate) { if (siteadmin == -1) { siteadmin = 0; } siteadmin |= 16; }
  1850. if (args.locked) { if (siteadmin == -1) { siteadmin = 0; } siteadmin |= 32; }
  1851. if (args.nonewgroups) { if (siteadmin == -1) { siteadmin = 0; } siteadmin |= 64; }
  1852. if (args.notools) { if (siteadmin == -1) { siteadmin = 0; } siteadmin |= 128; }
  1853. return siteadmin;
  1854. }
  1855. ws.on('close', function () { process.exit(); });
  1856. ws.on('error', function (err) {
  1857. if (err.code == 'ENOTFOUND') { console.log('Unable to resolve ' + url); }
  1858. else if (err.code == 'ECONNREFUSED') { console.log('Unable to connect to ' + url); }
  1859. else { console.log('Unable to connect to ' + url); }
  1860. process.exit();
  1861. });
  1862. ws.on('message', function incoming(rawdata) {
  1863. var data = null;
  1864. try { data = JSON.parse(rawdata); } catch (ex) { }
  1865. if (data == null) { console.log('Unable to parse data: ' + rawdata); }
  1866. if (settings.cmd == 'showevents') {
  1867. if (args.filter == null) {
  1868. // Display all events
  1869. console.log(JSON.stringify(data, null, 2));
  1870. } else {
  1871. // Display select events
  1872. var filters = args.filter.split(',');
  1873. if (typeof data.event == 'object') {
  1874. if (filters.indexOf(data.event.action) >= 0) { console.log(JSON.stringify(data, null, 2) + '\r\n'); }
  1875. } else {
  1876. if (filters.indexOf(data.action) >= 0) { console.log(JSON.stringify(data, null, 2) + '\r\n'); }
  1877. }
  1878. }
  1879. return;
  1880. }
  1881. switch (data.action) {
  1882. case 'serverinfo': { // SERVERINFO
  1883. settings.currentDomain = data.serverinfo.domain;
  1884. if (settings.cmd == 'serverinfo') {
  1885. if (args.json) {
  1886. console.log(JSON.stringify(data.serverinfo, ' ', 2));
  1887. } else {
  1888. for (var i in data.serverinfo) { console.log(i + ':', data.serverinfo[i]); }
  1889. }
  1890. process.exit();
  1891. }
  1892. break;
  1893. }
  1894. case 'events': {
  1895. if (settings.cmd == 'listevents') {
  1896. if (args.raw) {
  1897. // RAW JSON
  1898. console.log(JSON.stringify(data.events));
  1899. } else if (args.json) {
  1900. // Formatted JSON
  1901. console.log(JSON.stringify(data.events, null, 2));
  1902. } else {
  1903. if ((args.id == null) && (args.userid == null)) {
  1904. // CSV format
  1905. console.log("time,type,action,nodeid,userid,msg");
  1906. for (var i in data.events) {
  1907. var x = [];
  1908. x.push(data.events[i].time);
  1909. x.push(data.events[i].etype);
  1910. x.push(data.events[i].action);
  1911. x.push(data.events[i].nodeid);
  1912. x.push(data.events[i].userid);
  1913. x.push(data.events[i].msg);
  1914. console.log(csvFormatArray(x));
  1915. }
  1916. } else if (args.id != null) {
  1917. // CSV format
  1918. console.log("time,type,action,userid,msg");
  1919. for (var i in data.events) {
  1920. var x = [];
  1921. x.push(data.events[i].time);
  1922. x.push(data.events[i].etype);
  1923. x.push(data.events[i].action);
  1924. x.push(data.events[i].userid);
  1925. x.push(data.events[i].msg);
  1926. console.log(csvFormatArray(x));
  1927. }
  1928. } else if (args.userid != null) {
  1929. // CSV format
  1930. console.log("time,type,action,nodeid,msg");
  1931. for (var i in data.events) {
  1932. var x = [];
  1933. x.push(data.events[i].time);
  1934. x.push(data.events[i].etype);
  1935. x.push(data.events[i].action);
  1936. x.push(data.events[i].nodeid);
  1937. x.push(data.events[i].msg);
  1938. console.log(csvFormatArray(x));
  1939. }
  1940. }
  1941. }
  1942. process.exit();
  1943. }
  1944. break;
  1945. }
  1946. case 'authcookie': { // SHELL, UPLOAD, DOWNLOAD
  1947. if ((settings.cmd == 'shell') || (settings.cmd == 'upload') || (settings.cmd == 'download')) {
  1948. var protocol = 1; // Terminal
  1949. if ((settings.cmd == 'upload') || (settings.cmd == 'download')) { protocol = 5; } // Files
  1950. if ((args.id.split('/') != 3) && (settings.currentDomain != null)) { args.id = 'node/' + settings.currentDomain + '/' + args.id; }
  1951. var id = getRandomHex(6);
  1952. ws.send(JSON.stringify({ action: 'msg', nodeid: args.id, type: 'tunnel', usage: 1, value: '*/meshrelay.ashx?p=' + protocol + '&nodeid=' + args.id + '&id=' + id + '&rauth=' + data.rcookie, responseid: 'meshctrl' }));
  1953. connectTunnel(url.replace('/control.ashx', '/meshrelay.ashx?browser=1&p=' + protocol + '&nodeid=' + args.id + '&id=' + id + '&auth=' + data.cookie));
  1954. }
  1955. break;
  1956. }
  1957. case 'deviceShares': { // DEVICESHARING
  1958. if (data.result != null) {
  1959. console.log(data.result);
  1960. } else {
  1961. if ((data.deviceShares == null) || (data.deviceShares.length == 0)) {
  1962. console.log('No device sharing links for this device.');
  1963. } else {
  1964. if (args.json) {
  1965. console.log(data.deviceShares);
  1966. } else {
  1967. for (var i in data.deviceShares) {
  1968. var share = data.deviceShares[i];
  1969. var shareType = [];
  1970. if ((share.p & 1) != 0) { shareType.push("Terminal"); }
  1971. if ((share.p & 2) != 0) { if (share.viewOnly) { shareType.push("View Only Desktop"); } else { shareType.push("Desktop"); } }
  1972. if ((share.p & 4) != 0) { shareType.push("Files"); }
  1973. shareType = shareType.join(' + ');
  1974. if (shareType == '') { shareType = "Unknown"; }
  1975. var consent = [];
  1976. if ((share.consent & 0x0001) != 0) { consent.push("Desktop Notify"); }
  1977. if ((share.consent & 0x0008) != 0) { consent.push("Desktop Prompt"); }
  1978. if ((share.consent & 0x0040) != 0) { consent.push("Desktop Connection Toolbar"); }
  1979. if ((share.consent & 0x0002) != 0) { consent.push("Terminal Notify"); }
  1980. if ((share.consent & 0x0010) != 0) { consent.push("Terminal Prompt"); }
  1981. if ((share.consent & 0x0004) != 0) { consent.push("Files Notify"); }
  1982. if ((share.consent & 0x0020) != 0) { consent.push("Files Prompt"); }
  1983. console.log('----------');
  1984. console.log('Identifier: ' + share.publicid);
  1985. console.log('Type: ' + shareType);
  1986. console.log('UserId: ' + share.userid);
  1987. console.log('Guest Name: ' + share.guestName);
  1988. console.log('User Consent: ' + consent.join(', '));
  1989. if (share.startTime) { console.log('Start Time: ' + new Date(share.startTime).toLocaleString()); }
  1990. if (share.expireTime) { console.log('Expire Time: ' + new Date(share.expireTime).toLocaleString()); }
  1991. if (share.duration) { console.log('Duration: ' + share.duration + ' minute' + ((share.duration > 1) ? 's' : '')); }
  1992. if (share.recurring == 1) { console.log('Recurring: ' + 'Daily'); }
  1993. if (share.recurring == 2) { console.log('Recurring: ' + 'Weekly'); }
  1994. console.log('URL: ' + share.url);
  1995. }
  1996. }
  1997. }
  1998. }
  1999. process.exit();
  2000. break;
  2001. }
  2002. case 'userinfo': { // USERINFO
  2003. if (settings.cmd == 'userinfo') {
  2004. if (args.json) {
  2005. console.log(JSON.stringify(data.userinfo, ' ', 2));
  2006. } else {
  2007. for (var i in data.userinfo) { console.log(i + ':', data.userinfo[i]); }
  2008. }
  2009. process.exit();
  2010. }
  2011. break;
  2012. }
  2013. case 'getsysinfo': { // DEVICEINFO
  2014. if (settings.cmd == 'deviceinfo') {
  2015. settings.sysinfo = (data.result) ? null : data;
  2016. if (--settings.deviceinfocount == 0) { displayDeviceInfo(settings.sysinfo, settings.lastconnect, settings.networking, settings.nodes); process.exit(); }
  2017. }
  2018. break;
  2019. }
  2020. case 'lastconnect': {
  2021. if (settings.cmd == 'deviceinfo') {
  2022. settings.lastconnect = (data.result) ? null : data;
  2023. if (--settings.deviceinfocount == 0) { displayDeviceInfo(settings.sysinfo, settings.lastconnect, settings.networking, settings.nodes); process.exit(); }
  2024. }
  2025. break;
  2026. }
  2027. case 'getnetworkinfo': {
  2028. if (settings.cmd == 'deviceinfo') {
  2029. settings.networking = (data.result) ? null : data;
  2030. if (--settings.deviceinfocount == 0) { displayDeviceInfo(settings.sysinfo, settings.lastconnect, settings.networking, settings.nodes); process.exit(); }
  2031. }
  2032. break;
  2033. }
  2034. case 'msg': // SHELL
  2035. case 'toast': // TOAST
  2036. case 'adduser': // ADDUSER
  2037. case 'edituser': // EDITUSER
  2038. case 'removedevices': // REMOVEDEVICE
  2039. case 'changedevice': // EDITDEVICE
  2040. case 'deleteuser': // REMOVEUSER
  2041. case 'createmesh': // ADDDEVICEGROUP
  2042. case 'deletemesh': // REMOVEDEVICEGROUP
  2043. case 'editmesh': // EDITDEVICEGROUP
  2044. case 'wakedevices':
  2045. case 'changeDeviceMesh':
  2046. case 'addmeshuser': //
  2047. case 'removemeshuser': //
  2048. case 'wakedevices': //
  2049. case 'inviteAgent': //
  2050. case 'adddeviceuser': //
  2051. case 'createusergroup': //
  2052. case 'deleteusergroup': //
  2053. case 'runcommands':
  2054. case 'poweraction':
  2055. case 'addusertousergroup':
  2056. case 'removeuserfromusergroup':
  2057. case 'removeDeviceShare':
  2058. case 'userbroadcast': { // BROADCAST
  2059. if ((settings.cmd == 'shell') || (settings.cmd == 'upload') || (settings.cmd == 'download')) return;
  2060. if ((settings.multiresponse != null) && (settings.multiresponse > 1)) { settings.multiresponse--; break; }
  2061. if (data.responseid == 'meshctrl') {
  2062. if (data.meshid) { console.log(data.result, data.meshid); }
  2063. else if (data.userid) { console.log(data.result, data.userid); }
  2064. else console.log(data.result);
  2065. process.exit();
  2066. }
  2067. break;
  2068. }
  2069. case 'createDeviceShareLink':
  2070. if (data.result == 'OK') {
  2071. if (data.publicid) { console.log('ID: ' + data.publicid); }
  2072. console.log('URL: ' + data.url);
  2073. } else {
  2074. console.log(data.result);
  2075. }
  2076. process.exit();
  2077. break;
  2078. case 'createInviteLink':
  2079. if (data.responseid == 'meshctrl') {
  2080. if (data.url) { console.log(data.url); }
  2081. else console.log(data.result);
  2082. process.exit();
  2083. }
  2084. break;
  2085. case 'wssessioncount': { // LIST USER SESSIONS
  2086. if (args.json) {
  2087. console.log(JSON.stringify(data.wssessions, ' ', 2));
  2088. } else {
  2089. for (var i in data.wssessions) { console.log(i + ', ' + ((data.wssessions[i] > 1) ? (data.wssessions[i] + ' sessions.') : ("1 session."))); }
  2090. }
  2091. process.exit();
  2092. break;
  2093. }
  2094. case 'usergroups': { // LIST USER GROUPS
  2095. if (settings.cmd == 'listusergroups') {
  2096. if (args.json) {
  2097. console.log(JSON.stringify(data.ugroups, ' ', 2));
  2098. } else {
  2099. for (var i in data.ugroups) {
  2100. var x = i + ', ' + data.ugroups[i].name;
  2101. if (data.ugroups[i].desc && (data.ugroups[i].desc != '')) { x += ', ' + data.ugroups[i].desc; }
  2102. console.log(x);
  2103. var mesh = [], user = [], node = [];
  2104. if (data.ugroups[i].links != null) { for (var j in data.ugroups[i].links) { if (j.startsWith('mesh/')) { mesh.push(j); } if (j.startsWith('user/')) { user.push(j); } if (j.startsWith('node/')) { node.push(j); } } }
  2105. console.log(' Users:');
  2106. if (user.length > 0) { for (var j in user) { console.log(' ' + user[j]); } } else { console.log(' (None)'); }
  2107. console.log(' Device Groups:');
  2108. if (mesh.length > 0) { for (var j in mesh) { console.log(' ' + mesh[j] + ', ' + data.ugroups[i].links[mesh[j]].rights); } } else { console.log(' (None)'); }
  2109. console.log(' Devices:');
  2110. if (node.length > 0) { for (var j in node) { console.log(' ' + node[j] + ', ' + data.ugroups[i].links[node[j]].rights); } } else { console.log(' (None)'); }
  2111. }
  2112. }
  2113. process.exit();
  2114. } else if (settings.cmd == 'removeallusersfromusergroup') {
  2115. var ugrpid = args.groupid, exit = false;
  2116. if ((args.domain != null) && (userid.indexOf('/') < 0)) { ugrpid = 'ugrp/' + args.domain + '/' + ugrpid; }
  2117. var ugroup = data.ugroups[ugrpid];
  2118. if (ugroup == null) {
  2119. console.log('User group not found.');
  2120. exit = true;
  2121. } else {
  2122. var usercount = 0;
  2123. if (ugroup.links) {
  2124. for (var i in ugroup.links) {
  2125. if (i.startsWith('user/')) {
  2126. usercount++;
  2127. ws.send(JSON.stringify({ action: 'removeuserfromusergroup', ugrpid: ugrpid, userid: i, responseid: 'meshctrl' }));
  2128. console.log('Removing ' + i);
  2129. }
  2130. }
  2131. }
  2132. if (usercount == 0) { console.log('No users in this user group.'); exit = true; } else { settings.multiresponse = usercount; }
  2133. }
  2134. if (exit) { process.exit(); }
  2135. }
  2136. break;
  2137. }
  2138. case 'users': { // LISTUSERS
  2139. if (data.result) { console.log(data.result); process.exit(); return; }
  2140. if (args.filter) {
  2141. // Filter the list of users
  2142. var filters = args.filter.toLowerCase().split(',');
  2143. var filteredusers = [];
  2144. for (var i in data.users) {
  2145. var ok = false;
  2146. if ((filters.indexOf('2fa') >= 0) && ((data.users[i].otphkeys != null) || (data.users[i].otpkeys != null) || (data.users[i].otpsecret != null))) { ok = true; }
  2147. if ((filters.indexOf('no2fa') >= 0) && ((data.users[i].otphkeys == null) && (data.users[i].otpkeys == null) && (data.users[i].otpsecret == null))) { ok = true; }
  2148. if (ok == true) { filteredusers.push(data.users[i]); }
  2149. }
  2150. data.users = filteredusers;
  2151. }
  2152. if (args.json) {
  2153. console.log(JSON.stringify(data.users, ' ', 2));
  2154. } else {
  2155. if (args.idexists) { for (var i in data.users) { const u = data.users[i]; if ((u._id == args.idexists) || (u._id.split('/')[2] == args.idexists)) { console.log('1'); process.exit(); return; } } console.log('0'); process.exit(); return; }
  2156. if (args.nameexists) { for (var i in data.users) { const u = data.users[i]; if (u.name == args.nameexists) { console.log(u._id); process.exit(); return; } } process.exit(); return; }
  2157. console.log('id, name, email\r\n---------------');
  2158. for (var i in data.users) {
  2159. const u = data.users[i];
  2160. var t = "\"" + u._id.split('/')[2] + "\", \"" + u.name + "\"";
  2161. if (u.email != null) { t += ", \"" + u.email + "\""; }
  2162. console.log(t);
  2163. }
  2164. }
  2165. process.exit();
  2166. break;
  2167. }
  2168. case 'nodes': {
  2169. if (settings.cmd == 'deviceinfo') {
  2170. settings.nodes = (data.result) ? null : data;
  2171. if (--settings.deviceinfocount == 0) { displayDeviceInfo(settings.sysinfo, settings.lastconnect, settings.networking, settings.nodes); process.exit(); }
  2172. }
  2173. if ((settings.cmd == 'listdevices') && (data.responseid == 'meshctrl')) {
  2174. if ((data.result != null) && (data.result != 'ok')) {
  2175. console.log(data.result);
  2176. } else {
  2177. // Filter devices based on device id.
  2178. if (args.filterid) {
  2179. var filteridSplit = args.filterid.split(','), filters = [];
  2180. for (var i in filteridSplit) {
  2181. var f = filteridSplit[i].trim();
  2182. var g = f.split('/'); // If there is any / in the id, just grab the last part.
  2183. if (g.length > 0) { f = g[g.length - 1]; }
  2184. if (f != '') { filters.push(f); }
  2185. }
  2186. if (filters.length > 0) {
  2187. for (var mid in data.nodes) {
  2188. var filteredNodes = [];
  2189. for (var nid in data.nodes[mid]) {
  2190. var n = data.nodes[mid][nid], match = false;
  2191. for (var f in filters) { if (n._id.indexOf(filters[f]) >= 0) { match = true; } }
  2192. if (match) { filteredNodes.push(n); }
  2193. }
  2194. data.nodes[mid] = filteredNodes;
  2195. }
  2196. }
  2197. }
  2198. // Filter devices based on filter string
  2199. if (args.filter != null) {
  2200. for (var meshid in data.nodes) {
  2201. for (var d in data.nodes[meshid]) { data.nodes[meshid][d].meshid = meshid; }
  2202. data.nodes[meshid] = parseSearchOrInput(data.nodes[meshid], args.filter.toString().toLowerCase());
  2203. }
  2204. }
  2205. if (args.csv) {
  2206. // Return a flat list
  2207. var nodecount = 0;
  2208. for (var i in data.nodes) {
  2209. var devicesInMesh = data.nodes[i];
  2210. for (var j in devicesInMesh) {
  2211. var n = devicesInMesh[j];
  2212. nodecount++;
  2213. if (settings.xmeshes) {
  2214. console.log('\"' + settings.xmeshes[i]._id.split('/')[2] + '\",\"' + settings.xmeshes[i].name.split('\"').join('') + '\",\"' + n._id.split('/')[2] + '\",\"' + n.name.split('\"').join('') + '\",' + (n.icon ? n.icon : 0) + ',' + (n.conn ? n.conn : 0) + ',' + (n.pwr ? n.pwr : 0));
  2215. } else {
  2216. console.log('\"' + n._id.split('/')[2] + '\",\"' + n.name.split('\"').join('') + '\",' + (n.icon ? n.icon : 0) + ',' + (n.conn ? n.conn : 0) + ',' + (n.pwr ? n.pwr : 0));
  2217. }
  2218. }
  2219. }
  2220. if (nodecount == 0) { console.log('None'); }
  2221. } else if (args.count) {
  2222. // Return how many devices are in this group
  2223. var nodes = [];
  2224. for (var i in data.nodes) { var devicesInMesh = data.nodes[i]; for (var j in devicesInMesh) { nodes.push(devicesInMesh[j]); } }
  2225. console.log(nodes.length);
  2226. } else if (args.json) {
  2227. // Return all devices in JSON format
  2228. var nodes = [];
  2229. for (var i in data.nodes) {
  2230. const devicesInMesh = data.nodes[i];
  2231. for (var j in devicesInMesh) {
  2232. devicesInMesh[j].meshid = i; // Add device group id
  2233. if (settings.xmeshes && settings.xmeshes[i] && settings.xmeshes[i].name) { devicesInMesh[j].groupname = settings.xmeshes[i].name; } // Add device group name
  2234. nodes.push(devicesInMesh[j]);
  2235. }
  2236. }
  2237. console.log(JSON.stringify(nodes, ' ', 2));
  2238. } else {
  2239. // Display the list of nodes in text format
  2240. var nodecount = 0;
  2241. for (var i in data.nodes) {
  2242. var devicesInMesh = data.nodes[i];
  2243. if (devicesInMesh.length > 0) {
  2244. if (settings.xmeshes) { console.log('\r\nDevice group: \"' + settings.xmeshes[i].name.split('\"').join('') + '\"'); }
  2245. console.log('id, name, icon, conn, pwr\r\n-------------------------');
  2246. for (var j in devicesInMesh) {
  2247. var n = devicesInMesh[j];
  2248. nodecount++;
  2249. console.log('\"' + n._id.split('/')[2] + '\", \"' + n.name.split('\"').join('') + '\", ' + (n.icon ? n.icon : 0) + ', ' + (n.conn ? n.conn : 0) + ', ' + (n.pwr ? n.pwr : 0));
  2250. }
  2251. }
  2252. }
  2253. if (nodecount == 0) { console.log('None'); }
  2254. }
  2255. }
  2256. process.exit();
  2257. }
  2258. if ((settings.cmd == 'groupmessage') && (data.responseid == 'meshctrl')) {
  2259. if ((data.nodes != null)) {
  2260. for (var i in data.nodes) {
  2261. for (let index = 0; index < data.nodes[i].length; index++) {
  2262. const element = data.nodes[i][index];
  2263. ws.send(JSON.stringify({ action: 'msg', type: 'messagebox', nodeid: element._id, title: args.title ? args.title : "MeshCentral", msg: args.msg, timeout: args.timeout ? args.timeout : 120000 }));
  2264. }
  2265. }
  2266. }
  2267. setTimeout(function(){ console.log('ok'); process.exit(); }, 1000);
  2268. }
  2269. if ((settings.cmd == 'grouptoast') && (data.responseid == 'meshctrl')) {
  2270. if (data.nodes != null) {
  2271. for (var i in data.nodes) {
  2272. var nodes = [];
  2273. for (let index = 0; index < data.nodes[i].length; index++) {
  2274. const element = data.nodes[i][index];
  2275. nodes.push(element._id);
  2276. }
  2277. ws.send(JSON.stringify({ action: 'toast', nodeids: nodes, title: args.title ? args.title : "MeshCentral", msg: args.msg, responseid: 'meshctrl' }));
  2278. }
  2279. }
  2280. }
  2281. break;
  2282. }
  2283. case 'meshes': { // LISTDEVICEGROUPS
  2284. if (settings.cmd == 'listdevices') {
  2285. // Store the list of device groups for later use
  2286. settings.xmeshes = {}
  2287. for (var i in data.meshes) { settings.xmeshes[data.meshes[i]._id] = data.meshes[i]; }
  2288. } else if (settings.cmd == 'listdevicegroups') {
  2289. if (args.json) {
  2290. // If asked, add the MeshID hex encoding to the JSON.
  2291. if (args.hex) { for (var i in data.meshes) { data.meshes[i]._idhex = '0x' + Buffer.from(data.meshes[i]._id.split('/')[2].replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase(); } }
  2292. console.log(JSON.stringify(data.meshes, ' ', 2));
  2293. } else {
  2294. if (args.idexists) { for (var i in data.meshes) { const u = data.meshes[i]; if ((u._id == args.idexists) || (u._id.split('/')[2] == args.idexists)) { console.log('1'); process.exit(); return; } } console.log('0'); process.exit(); return; }
  2295. if (args.nameexists) { for (var i in data.meshes) { const u = data.meshes[i]; if (u.name == args.nameexists) { console.log(u._id); process.exit(); return; } } process.exit(); return; }
  2296. console.log('id, name\r\n---------------');
  2297. for (var i in data.meshes) {
  2298. const m = data.meshes[i];
  2299. var mid = m._id.split('/')[2];
  2300. if (args.hex) { mid = '0x' + Buffer.from(mid.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase(); }
  2301. var t = "\"" + mid + "\", \"" + m.name + "\"";
  2302. console.log(t);
  2303. }
  2304. }
  2305. process.exit();
  2306. } else if (settings.cmd == 'listusersofdevicegroup') {
  2307. for (var i in data.meshes) {
  2308. const m = data.meshes[i];
  2309. var mid = m._id.split('/')[2];
  2310. if (mid == args.id) {
  2311. if (args.json) {
  2312. console.log(JSON.stringify(m.links, ' ', 2));
  2313. } else {
  2314. console.log('userid, rights\r\n---------------');
  2315. for (var l in m.links) {
  2316. var rights = m.links[l].rights;
  2317. var rightsstr = [];
  2318. if (rights == 4294967295) { rightsstr = ['FullAdministrator']; } else {
  2319. if (rights & 1) { rightsstr.push('EditMesh'); }
  2320. if (rights & 2) { rightsstr.push('ManageUsers'); }
  2321. if (rights & 4) { rightsstr.push('ManageComputers'); }
  2322. if (rights & 8) { rightsstr.push('RemoteControl'); }
  2323. if (rights & 16) { rightsstr.push('AgentConsole'); }
  2324. if (rights & 32) { rightsstr.push('ServerFiles'); }
  2325. if (rights & 64) { rightsstr.push('WakeDevice'); }
  2326. if (rights & 128) { rightsstr.push('SetNotes'); }
  2327. if (rights & 256) { rightsstr.push('RemoteViewOnly'); }
  2328. if (rights & 512) { rightsstr.push('NoTerminal'); }
  2329. if (rights & 1024) { rightsstr.push('NoFiles'); }
  2330. if (rights & 2048) { rightsstr.push('NoAMT'); }
  2331. if (rights & 4096) { rightsstr.push('DesktopLimitedInput'); }
  2332. }
  2333. console.log(l.split('/')[2] + ', ' + rightsstr.join(', '));
  2334. }
  2335. }
  2336. process.exit();
  2337. return;
  2338. }
  2339. }
  2340. console.log('Group id not found');
  2341. process.exit();
  2342. }
  2343. break;
  2344. }
  2345. case 'close': {
  2346. if (data.cause == 'noauth') {
  2347. if (data.msg == 'tokenrequired') {
  2348. console.log('Authentication token required, use --token [number].');
  2349. } else if (data.msg == 'nokey') {
  2350. console.log('URL key is invalid or missing, please specify ?key=xxx in url');
  2351. } else {
  2352. if ((args.loginkeyfile != null) || (args.loginkey != null)) {
  2353. console.log('Invalid login, check the login key and that this computer has the correct time.');
  2354. } else {
  2355. console.log('Invalid login.');
  2356. }
  2357. }
  2358. }
  2359. process.exit();
  2360. break;
  2361. }
  2362. case 'createLoginToken': {
  2363. if (data.result != null) {
  2364. console.log(data.result);
  2365. process.exit();
  2366. } else {
  2367. if (args.json) {
  2368. console.log(data);
  2369. } else {
  2370. console.log("New login token created.");
  2371. if (data.name) { console.log("Token name: " + data.name); }
  2372. if (data.created) { console.log("Created: " + new Date(data.created).toLocaleString()); }
  2373. if (data.expire) { console.log("Expire: " + new Date(data.expire).toLocaleString()); }
  2374. if (data.tokenUser) { console.log("Username: " + data.tokenUser); }
  2375. if (data.tokenPass) { console.log("Password: " + data.tokenPass); }
  2376. }
  2377. }
  2378. process.exit();
  2379. break;
  2380. }
  2381. case 'loginTokens': {
  2382. if (args.json) {
  2383. console.log(data.loginTokens);
  2384. } else {
  2385. console.log("Name Username Expire");
  2386. console.log("-------------------------------------------------------------------------------------");
  2387. if (data.loginTokens.length == 0) {
  2388. console.log("No login tokens");
  2389. } else {
  2390. for (var i in data.loginTokens) {
  2391. var t = data.loginTokens[i];
  2392. var e = (t.expire == 0) ? "Unlimited" : new Date(t.expire).toLocaleString();
  2393. console.log(padString(t.name, 28) + padString(t.tokenUser, 28) + e);
  2394. }
  2395. }
  2396. }
  2397. process.exit();
  2398. break;
  2399. }
  2400. case 'getDeviceDetails': {
  2401. console.log(data.data);
  2402. process.exit();
  2403. }
  2404. case 'report': {
  2405. console.log('group,' + data.data.columns.flatMap(c => c.id).join(','));
  2406. Object.keys(data.data.groups).forEach(gk => {
  2407. data.data.groups[gk].entries.forEach(e => {
  2408. console.log(gk + ',' + Object.values(e).join(','));
  2409. });
  2410. });
  2411. process.exit();
  2412. }
  2413. default: { break; }
  2414. }
  2415. //console.log('Data', data);
  2416. //setTimeout(function timeout() { ws.send(Date.now()); }, 500);
  2417. });
  2418. }
  2419. // String padding function
  2420. function padString(str, pad) {
  2421. var xpad = ' ';
  2422. if (str.length >= pad) return str; return str + xpad.substring(0, pad - str.length)
  2423. }
  2424. function parseSearchAndInput(nodes, x) {
  2425. var s = x.split(' ' + "and" + ' '), r = null;
  2426. for (var i in s) {
  2427. var r2 = getDevicesThatMatchFilter(nodes, s[i]);
  2428. if (r == null) { r = r2; } else { var r3 = []; for (var j in r2) { if (r.indexOf(r2[j]) >= 0) { r3.push(r2[j]); } } r = r3; }
  2429. }
  2430. return r;
  2431. }
  2432. function parseSearchOrInput(nodes, x) {
  2433. var s = x.split(' ' + "or" + ' '), r = null;
  2434. for (var i in s) { var r2 = parseSearchAndInput(nodes, s[i]); if (r == null) { r = r2; } else { for (var j in r2) { if (r.indexOf(r2[j] >= 0)) { r.push(r2[j]); } } } }
  2435. return r;
  2436. }
  2437. function getDevicesThatMatchFilter(nodes, x) {
  2438. var r = [];
  2439. var userSearch = null, ipSearch = null, groupSearch = null, tagSearch = null, agentTagSearch = null, wscSearch = null, osSearch = null, amtSearch = null, descSearch = null;
  2440. if (x.startsWith("user:".toLowerCase())) { userSearch = x.substring("user:".length); }
  2441. else if (x.startsWith("u:".toLowerCase())) { userSearch = x.substring("u:".length); }
  2442. else if (x.startsWith("ip:".toLowerCase())) { ipSearch = x.substring("ip:".length); }
  2443. else if (x.startsWith("group:".toLowerCase())) { groupSearch = x.substring("group:".length); }
  2444. else if (x.startsWith("g:".toLowerCase())) { groupSearch = x.substring("g:".length); }
  2445. else if (x.startsWith("tag:".toLowerCase())) { tagSearch = x.substring("tag:".length); }
  2446. else if (x.startsWith("t:".toLowerCase())) { tagSearch = x.substring("t:".length); }
  2447. else if (x.startsWith("atag:".toLowerCase())) { agentTagSearch = x.substring("atag:".length); }
  2448. else if (x.startsWith("a:".toLowerCase())) { agentTagSearch = x.substring("a:".length); }
  2449. else if (x.startsWith("os:".toLowerCase())) { osSearch = x.substring("os:".length); }
  2450. else if (x.startsWith("amt:".toLowerCase())) { amtSearch = x.substring("amt:".length); }
  2451. else if (x.startsWith("desc:".toLowerCase())) { descSearch = x.substring("desc:".length); }
  2452. else if (x == 'wsc:ok') { wscSearch = 1; }
  2453. else if (x == 'wsc:noav') { wscSearch = 2; }
  2454. else if (x == 'wsc:noupdate') { wscSearch = 3; }
  2455. else if (x == 'wsc:nofirewall') { wscSearch = 4; }
  2456. else if (x == 'wsc:any') { wscSearch = 5; }
  2457. if (x == '') {
  2458. // No search
  2459. for (var d in nodes) { r.push(nodes[d]); }
  2460. } else if (ipSearch != null) {
  2461. // IP address search
  2462. for (var d in nodes) { if ((nodes[d].ip != null) && (nodes[d].ip.indexOf(ipSearch) >= 0)) { r.push(nodes[d]); } }
  2463. } else if (groupSearch != null) {
  2464. // Group filter
  2465. if (settings.xmeshes) { for (var d in nodes) { if (settings.xmeshes[nodes[d].meshid].name.toLowerCase().indexOf(groupSearch) >= 0) { r.push(nodes[d]); } } }
  2466. } else if (tagSearch != null) {
  2467. // Tag filter
  2468. for (var d in nodes) {
  2469. if ((nodes[d].tags == null) && (tagSearch == '')) { r.push(d); }
  2470. else if (nodes[d].tags != null) { for (var j in nodes[d].tags) { if (nodes[d].tags[j].toLowerCase() == tagSearch) { r.push(d); break; } } }
  2471. }
  2472. } else if (agentTagSearch != null) {
  2473. // Agent Tag filter
  2474. for (var d in nodes) {
  2475. if ((((nodes[d].agent != null) && (nodes[d].agent.tag == null)) && (agentTagSearch == '')) || ((nodes[d].agent != null) && (nodes[d].agent.tag != null) && (nodes[d].agent.tag.toLowerCase().indexOf(agentTagSearch) >= 0))) { r.push(nodes[d]); };
  2476. }
  2477. } else if (userSearch != null) {
  2478. // User search
  2479. for (var d in nodes) {
  2480. if (nodes[d].users && nodes[d].users.length > 0) { for (var i in nodes[d].users) { if (nodes[d].users[i].toLowerCase().indexOf(userSearch) >= 0) { r.push(nodes[d]); } } }
  2481. }
  2482. } else if (osSearch != null) {
  2483. // OS search
  2484. for (var d in nodes) { if ((nodes[d].osdesc != null) && (nodes[d].osdesc.toLowerCase().indexOf(osSearch) >= 0)) { r.push(nodes[d]); }; }
  2485. } else if (amtSearch != null) {
  2486. // Intel AMT search
  2487. for (var d in nodes) { if ((nodes[d].intelamt != null) && ((amtSearch == '') || (nodes[d].intelamt.state == amtSearch))) { r.push(nodes[d]); } }
  2488. } else if (descSearch != null) {
  2489. // Device description search
  2490. for (var d in nodes) { if ((nodes[d].desc != null) && (nodes[d].desc != '') && ((descSearch == '') || (nodes[d].desc.toLowerCase().indexOf(descSearch) >= 0))) { r.push(nodes[d]); } }
  2491. } else if (wscSearch != null) {
  2492. // Windows Security Center
  2493. for (var d in nodes) {
  2494. if (nodes[d].wsc) {
  2495. if ((wscSearch == 1) && (nodes[d].wsc.antiVirus == 'OK') && (nodes[d].wsc.autoUpdate == 'OK') && (nodes[d].wsc.firewall == 'OK')) { r.push(nodes[d]); }
  2496. else if (((wscSearch == 2) || (wscSearch == 5)) && (nodes[d].wsc.antiVirus != 'OK')) { r.push(nodes[d]); }
  2497. else if (((wscSearch == 3) || (wscSearch == 5)) && (nodes[d].wsc.autoUpdate != 'OK')) { r.push(nodes[d]); }
  2498. else if (((wscSearch == 4) || (wscSearch == 5)) && (nodes[d].wsc.firewall != 'OK')) { r.push(nodes[d]); }
  2499. }
  2500. }
  2501. } else if (x == '*') {
  2502. // Star filter
  2503. for (var d in nodes) { if (stars[nodes[d]._id] == 1) { r.push(nodes[d]); } }
  2504. } else {
  2505. // Device name search
  2506. try {
  2507. var rs = x.split(/\s+/).join('|'), rx = new RegExp(rs); // In some cases (like +), this can throw an exception.
  2508. for (var d in nodes) {
  2509. //if (showRealNames) {
  2510. //if (nodes[d].rnamel != null && rx.test(nodes[d].rnamel.toLowerCase())) { r.push(nodes[d]); }
  2511. //} else {
  2512. if (rx.test(nodes[d].name.toLowerCase())) { r.push(nodes[d]); }
  2513. //}
  2514. }
  2515. } catch (ex) { for (var d in nodes) { r.push(nodes[d]); } }
  2516. }
  2517. return r;
  2518. }
  2519. // Connect tunnel to a remote agent
  2520. function connectTunnel(url) {
  2521. // Setup WebSocket options
  2522. var options = { rejectUnauthorized: false, checkServerIdentity: onVerifyServer }
  2523. // Setup the HTTP proxy if needed
  2524. if (args.proxy != null) { const HttpsProxyAgent = require('https-proxy-agent'); options.agent = new HttpsProxyAgent(require('url').parse(args.proxy)); }
  2525. // Connect the WebSocket
  2526. console.log('Connecting...');
  2527. const WebSocket = require('ws');
  2528. settings.tunnelwsstate = 0;
  2529. settings.tunnelws = new WebSocket(url, options);
  2530. settings.tunnelws.on('open', function () { console.log('Waiting for Agent...'); }); // Wait for agent connection
  2531. settings.tunnelws.on('close', function () { console.log('Connection Closed.'); process.exit(); });
  2532. settings.tunnelws.on('error', function (err) { console.log(err); process.exit(); });
  2533. if (settings.cmd == 'shell') {
  2534. // This code does all of the work for a shell command
  2535. settings.tunnelws.on('message', function (rawdata) {
  2536. var data = rawdata.toString();
  2537. if (settings.tunnelwsstate == 1) {
  2538. // If the incoming text looks exactly like a control command, ignore it.
  2539. if ((typeof data == 'string') && (data.startsWith('{"ctrlChannel":"102938","type":"'))) {
  2540. var ctrlCmd = null;
  2541. try { ctrlCmd = JSON.parse(data); } catch (ex) { }
  2542. if ((ctrlCmd != null) && (ctrlCmd.ctrlChannel == '102938') && (ctrlCmd.type != null)) return; // This is a control command, like ping/pong. Ignore it.
  2543. }
  2544. process.stdout.write(data);
  2545. } else if (settings.tunnelwsstate == 0) {
  2546. if (data == 'c') { console.log('Connected.'); } else if (data == 'cr') { console.log('Connected, session is being recorded.'); } else return;
  2547. // Send terminal size
  2548. var termSize = null;
  2549. if (typeof process.stdout.getWindowSize == 'function') { termSize = process.stdout.getWindowSize(); }
  2550. if (termSize != null) { settings.tunnelws.send(JSON.stringify({ ctrlChannel: '102938', type: 'options', cols: termSize[0], rows: termSize[1] })); }
  2551. settings.tunnelwsstate = 1;
  2552. settings.tunnelws.send('1'); // Terminal
  2553. process.stdin.setEncoding('utf8');
  2554. process.stdin.setRawMode(true);
  2555. process.stdout.setEncoding('utf8');
  2556. process.stdin.unpipe(process.stdout);
  2557. process.stdout.unpipe(process.stdin);
  2558. process.stdin.on('data', function (data) { settings.tunnelws.send(Buffer.from(data)); });
  2559. //process.stdin.on('readable', function () { var chunk; while ((chunk = process.stdin.read()) !== null) { settings.tunnelws.send(Buffer.from(chunk)); } });
  2560. process.stdin.on('end', function () { process.exit(); });
  2561. process.stdout.on('resize', function () {
  2562. var termSize = null;
  2563. if (typeof process.stdout.getWindowSize == 'function') { termSize = process.stdout.getWindowSize(); }
  2564. if (termSize != null) { settings.tunnelws.send(JSON.stringify({ ctrlChannel: '102938', type: 'termsize', cols: termSize[0], rows: termSize[1] })); }
  2565. });
  2566. }
  2567. });
  2568. } else if (settings.cmd == 'upload') {
  2569. // This code does all of the work for a file upload
  2570. // node meshctrl upload --id oL4Y6Eg0qjnpHFrp1AxfxnBPenbDGnDSkC@HSOnAheIyd51pKhqSCUgJZakzwfKl --file readme.md --target c:\
  2571. settings.tunnelws.on('message', function (rawdata) {
  2572. if (settings.tunnelwsstate == 1) {
  2573. var cmd = null;
  2574. try { cmd = JSON.parse(rawdata.toString()); } catch (ex) { return; }
  2575. if (cmd.reqid == 'up') {
  2576. if ((cmd.action == 'uploadack') || (cmd.action == 'uploadstart')) {
  2577. settings.inFlight--;
  2578. if (settings.uploadFile == null) { if (settings.inFlight == 0) { process.exit(); } return; } // If the file is closed and there is no more in-flight data, exit.
  2579. var loops = (cmd.action == 'uploadstart') ? 16 : 1; // If this is the first data to be sent, hot start now. We are going to have 16 blocks of data in-flight.
  2580. for (var i = 0; i < loops; i++) {
  2581. if (settings.uploadFile == null) continue;
  2582. var buf = Buffer.alloc(65565);
  2583. var len = require('fs').readSync(settings.uploadFile, buf, 1, 65564, settings.uploadPtr);
  2584. var start = 1;
  2585. settings.uploadPtr += len;
  2586. if (len > 0) {
  2587. if ((buf[1] == 0) || (buf[1] == 123)) { start = 0; buf[0] = 0; len++; } // If the buffer starts with 0 or 123, we must add an extra 0 at the start of the buffer
  2588. settings.inFlight++;
  2589. settings.tunnelws.send(buf.slice(start, start + len));
  2590. } else {
  2591. console.log('Upload done, ' + settings.uploadPtr + ' bytes sent.');
  2592. if (settings.uploadFile != null) { require('fs').closeSync(settings.uploadFile); delete settings.uploadFile; }
  2593. if (settings.inFlight == 0) { process.exit(); return; } // File is closed, if there is no more in-flight data, exit.
  2594. }
  2595. }
  2596. } else if (cmd.action == 'uploaderror') {
  2597. if (settings.uploadFile != null) { require('fs').closeSync(settings.uploadFile); }
  2598. console.log('Upload error.');
  2599. process.exit();
  2600. }
  2601. }
  2602. } else if (settings.tunnelwsstate == 0) {
  2603. var data = rawdata.toString();
  2604. if (data == 'c') { console.log('Connected.'); } else if (data == 'cr') { console.log('Connected, session is being recorded.'); } else return;
  2605. settings.tunnelwsstate = 1;
  2606. settings.tunnelws.send('5'); // Files
  2607. settings.uploadSize = require('fs').statSync(args.file).size;
  2608. settings.uploadFile = require('fs').openSync(args.file, 'r');
  2609. settings.uploadPtr = 0;
  2610. settings.inFlight = 1;
  2611. console.log('Uploading...');
  2612. settings.tunnelws.send(JSON.stringify({ action: 'upload', reqid: 'up', path: args.target, name: require('path').basename(args.file), size: settings.uploadSize }));
  2613. }
  2614. });
  2615. } else if (settings.cmd == 'download') {
  2616. // This code does all of the work for a file download
  2617. // node meshctrl download --id oL4Y6Eg0qjnpHFrp1AxfxnBPenbDGnDSkC@HSOnAheIyd51pKhqSCUgJZakzwfKl --file c:\temp\MC-8Languages.png --target c:\temp\bob.png
  2618. settings.tunnelws.on('message', function (rawdata) {
  2619. if (settings.tunnelwsstate == 1) {
  2620. if ((rawdata.length > 0) && (rawdata.toString()[0] != '{')) {
  2621. // This is binary data, this test is ok because 4 first bytes is a control value.
  2622. if ((rawdata.length > 4) && (settings.downloadFile != null)) { settings.downloadSize += (rawdata.length - 4); require('fs').writeSync(settings.downloadFile, rawdata, 4, rawdata.length - 4); }
  2623. if ((rawdata[3] & 1) != 0) { // Check end flag
  2624. // File is done, close everything.
  2625. if (settings.downloadFile != null) { require('fs').closeSync(settings.downloadFile); }
  2626. console.log('Download completed, ' + settings.downloadSize + ' bytes written.');
  2627. process.exit();
  2628. } else {
  2629. settings.tunnelws.send(JSON.stringify({ action: 'download', sub: 'ack', id: args.file })); // Send the ACK
  2630. }
  2631. } else {
  2632. // This is text data
  2633. var cmd = null;
  2634. try { cmd = JSON.parse(rawdata.toString()); } catch (ex) { return; }
  2635. if (cmd.action == 'download') {
  2636. if (cmd.id != args.file) return;
  2637. if (cmd.sub == 'start') {
  2638. if ((args.target.endsWith('\\')) || (args.target.endsWith('/'))) { args.target += path.parse(args.file).name; }
  2639. try { settings.downloadFile = require('fs').openSync(args.target, 'w'); } catch (ex) { console.log("Unable to create file: " + args.target); process.exit(); return; }
  2640. settings.downloadSize = 0;
  2641. settings.tunnelws.send(JSON.stringify({ action: 'download', sub: 'startack', id: args.file }));
  2642. console.log('Download started: ' + args.target);
  2643. } else if (cmd.sub == 'cancel') {
  2644. if (settings.downloadFile != null) { require('fs').closeSync(settings.downloadFile); }
  2645. console.log('Download canceled.');
  2646. process.exit();
  2647. }
  2648. }
  2649. }
  2650. } else if (settings.tunnelwsstate == 0) {
  2651. var data = rawdata.toString();
  2652. if (data == 'c') { console.log('Connected.'); } else if (data == 'cr') { console.log('Connected, session is being recorded.'); } else return;
  2653. settings.tunnelwsstate = 1;
  2654. settings.tunnelws.send('5'); // Files
  2655. settings.tunnelws.send(JSON.stringify({ action: 'download', sub: 'start', id: args.file, path: args.file }));
  2656. }
  2657. });
  2658. }
  2659. }
  2660. // Encode an object as a cookie using a key using AES-GCM. (key must be 32 bytes or more)
  2661. function encodeCookie(o, key) {
  2662. try {
  2663. if (key == null) { return null; }
  2664. o.time = Math.floor(Date.now() / 1000); // Add the cookie creation time
  2665. const iv = Buffer.from(crypto.randomBytes(12), 'binary'), cipher = crypto.createCipheriv('aes-256-gcm', key.slice(0, 32), iv);
  2666. const crypted = Buffer.concat([cipher.update(JSON.stringify(o), 'utf8'), cipher.final()]);
  2667. return Buffer.concat([iv, cipher.getAuthTag(), crypted]).toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
  2668. } catch (e) { return null; }
  2669. }
  2670. // Generate a random Intel AMT password
  2671. function checkAmtPassword(p) { return (p.length > 7) && (/\d/.test(p)) && (/[a-z]/.test(p)) && (/[A-Z]/.test(p)) && (/\W/.test(p)); }
  2672. function getRandomAmtPassword() { var p; do { p = Buffer.from(crypto.randomBytes(9), 'binary').toString('base64').split('/').join('@'); } while (checkAmtPassword(p) == false); return p; }
  2673. function getRandomHex(count) { return Buffer.from(crypto.randomBytes(count), 'binary').toString('hex'); }
  2674. function format(format) { var args = Array.prototype.slice.call(arguments, 1); return format.replace(/{(\d+)}/g, function (match, number) { return typeof args[number] != 'undefined' ? args[number] : match; }); };
  2675. function winRemoveSingleQuotes(str) { if (process.platform != 'win32') return str; else return str.split('\'').join(''); }
  2676. function csvFormatArray(x) {
  2677. var y = [];
  2678. for (var i in x) { if ((x[i] == null) || (x[i] == '')) { y.push(''); } else { y.push('"' + x[i].split('"').join('') + '"'); } }
  2679. return y.join(',');
  2680. }
  2681. function displayDeviceInfo(sysinfo, lastconnect, network, nodes) {
  2682. //console.log('displayDeviceInfo', sysinfo, lastconnect, network, nodes);
  2683. // Fetch the node information
  2684. var node = null;;
  2685. if (sysinfo != null && (sysinfo.node != null)) {
  2686. // Node information came with system information
  2687. node = sysinfo.node;
  2688. } else {
  2689. // This device does not have system information, get node information from the nodes list.
  2690. for (var m in nodes.nodes) {
  2691. for (var n in nodes.nodes[m]) {
  2692. if (nodes.nodes[m][n]._id.indexOf(args.id) >= 0) { node = nodes.nodes[m][n]; }
  2693. }
  2694. }
  2695. }
  2696. if ((sysinfo == null && lastconnect == null && network == null) || (node == null)) {
  2697. console.log("Invalid device id");
  2698. process.exit(); return;
  2699. }
  2700. var info = {};
  2701. //if (network != null) { sysinfo.netif = network.netif; }
  2702. if (lastconnect != null) { node.lastconnect = lastconnect.time; node.lastaddr = lastconnect.addr; }
  2703. if (args.raw) { console.log(JSON.stringify(sysinfo, ' ', 2)); return; }
  2704. // General
  2705. var output = {}, outputCount = 0;
  2706. if (node.name) { output["Server Name"] = node.name; outputCount++; }
  2707. if (node.rname) { output["Computer Name"] = node.rname; outputCount++; }
  2708. if (node.host != null) { output["Hostname"] = node.host; outputCount++; }
  2709. if (node.ip != null) { output["IP Address"] = node.ip; outputCount++; }
  2710. if (node.desc != null) { output["Description"] = node.desc; outputCount++; }
  2711. if (node.icon != null) { output["Icon"] = node.icon; outputCount++; }
  2712. if (node.tags) { output["Tags"] = node.tags; outputCount++; }
  2713. if (node.av) {
  2714. var av = [];
  2715. for (var i in node.av) {
  2716. if (typeof node.av[i]['product'] == 'string') {
  2717. var n = node.av[i]['product'];
  2718. if (node.av[i]['updated'] === true) { n += ', updated'; }
  2719. if (node.av[i]['updated'] === false) { n += ', not updated'; }
  2720. if (node.av[i]['enabled'] === true) { n += ', enabled'; }
  2721. if (node.av[i]['enabled'] === false) { n += ', disabled'; }
  2722. av.push(n);
  2723. }
  2724. }
  2725. output["AntiVirus"] = av; outputCount++;
  2726. }
  2727. if (typeof node.wsc == 'object') {
  2728. output["WindowsSecurityCenter"] = node.wsc; outputCount++;
  2729. }
  2730. if (outputCount > 0) { info["General"] = output; }
  2731. // Operating System
  2732. var hardware = null;
  2733. if ((sysinfo != null) && (sysinfo.hardware != null)) { hardware = sysinfo.hardware; }
  2734. if ((hardware && hardware.windows && hardware.windows.osinfo) || node.osdesc) {
  2735. var output = {}, outputCount = 0;
  2736. if (node.rname) { output["Name"] = node.rname; outputCount++; }
  2737. if (node.osdesc) { output["Version"] = node.osdesc; outputCount++; }
  2738. if (hardware && hardware.windows && hardware.windows.osinfo) { var m = hardware.windows.osinfo; if (m.OSArchitecture) { output["Architecture"] = m.OSArchitecture; outputCount++; } }
  2739. if (outputCount > 0) { info["Operating System"] = output; }
  2740. }
  2741. // MeshAgent
  2742. if (node.agent) {
  2743. var output = {}, outputCount = 0;
  2744. var agentsStr = ["Unknown", "Windows 32bit console", "Windows 64bit console", "Windows 32bit service", "Windows 64bit service", "Linux 32bit", "Linux 64bit", "MIPS", "XENx86", "Android", "Linux ARM", "macOS x86-32bit", "Android x86", "PogoPlug ARM", "Android", "Linux Poky x86-32bit", "macOS x86-64bit", "ChromeOS", "Linux Poky x86-64bit", "Linux NoKVM x86-32bit", "Linux NoKVM x86-64bit", "Windows MinCore console", "Windows MinCore service", "NodeJS", "ARM-Linaro", "ARMv6l / ARMv7l", "ARMv8 64bit", "ARMv6l / ARMv7l / NoKVM", "MIPS24KC (OpenWRT)", "Apple Silicon", "FreeBSD x86-64", "Unknown", "Linux ARM 64 bit (glibc/2.24 NOKVM)", "Alpine Linux x86 64 Bit (MUSL)", "Assistant (Windows)", "Armada370 - ARM32/HF (libc/2.26)", "OpenWRT x86-64", "OpenBSD x86-64", "Unknown", "Unknown", "MIPSEL24KC (OpenWRT)", "ARMADA/CORTEX-A53/MUSL (OpenWRT)", "Windows ARM 64bit console", "Windows ARM 64bit service"];
  2745. if ((node.agent != null) && (node.agent.id != null) && (node.agent.ver != null)) {
  2746. var str = '';
  2747. if (node.agent.id <= agentsStr.length) { str = agentsStr[node.agent.id]; } else { str = agentsStr[0]; }
  2748. if (node.agent.ver != 0) { str += ' v' + node.agent.ver; }
  2749. output["Mesh Agent"] = str; outputCount++;
  2750. }
  2751. if ((node.conn & 1) != 0) {
  2752. output["Last agent connection"] = "Connected now"; outputCount++;
  2753. } else {
  2754. if (node.lastconnect) { output["Last agent connection"] = new Date(node.lastconnect).toLocaleString(); outputCount++; }
  2755. }
  2756. if (node.lastaddr) {
  2757. var splitip = node.lastaddr.split(':');
  2758. if (splitip.length > 2) {
  2759. output["Last agent address"] = node.lastaddr; outputCount++; // IPv6
  2760. } else {
  2761. output["Last agent address"] = splitip[0]; outputCount++; // IPv4
  2762. }
  2763. }
  2764. if ((node.agent != null) && (node.agent.tag != null)) {
  2765. output["Tag"] = node.agent.tag; outputCount++;
  2766. }
  2767. if (outputCount > 0) { info["Mesh Agent"] = output; }
  2768. }
  2769. // Networking
  2770. if (network.netif != null) {
  2771. var output = {}, outputCount = 0, minfo = {};
  2772. for (var i in network.netif) {
  2773. var m = network.netif[i], moutput = {}, moutputCount = 0;
  2774. if (m.desc) { moutput["Description"] = m.desc; moutputCount++; }
  2775. if (m.mac) {
  2776. if (m.gatewaymac) {
  2777. moutput["MAC Layer"] = format("MAC: {0}, Gateway: {1}", m.mac, m.gatewaymac); moutputCount++;
  2778. } else {
  2779. moutput["MAC Layer"] = format("MAC: {0}", m.mac); moutputCount++;
  2780. }
  2781. }
  2782. if (m.v4addr && (m.v4addr != '0.0.0.0')) {
  2783. if (m.v4gateway && m.v4mask) {
  2784. moutput["IPv4 Layer"] = format("IP: {0}, Mask: {1}, Gateway: {2}", m.v4addr, m.v4mask, m.v4gateway); moutputCount++;
  2785. } else {
  2786. moutput["IPv4 Layer"] = format("IP: {0}", m.v4addr); moutputCount++;
  2787. }
  2788. }
  2789. if (moutputCount > 0) { minfo[m.name + (m.dnssuffix ? (', ' + m.dnssuffix) : '')] = moutput; info["Networking"] = minfo; }
  2790. }
  2791. }
  2792. if (network.netif2 != null) {
  2793. var minfo = {};
  2794. for (var i in network.netif2) {
  2795. var m = network.netif2[i], moutput = {}, moutputCount = 0;
  2796. if (Array.isArray(m) == false ||
  2797. m.length < 1 ||
  2798. m[0] == null ||
  2799. ((typeof m[0].mac == 'string') && (m[0].mac.startsWith('00:00:00:00')))
  2800. )
  2801. continue;
  2802. var ifTitle = '' + i;
  2803. if (m[0].fqdn != null && m[0].fqdn != '') ifTitle += ', ' + m[0].fqdn;
  2804. if (typeof m[0].mac == 'string') {
  2805. if (m[0].gatewaymac) {
  2806. moutput['MAC Layer'] = format("MAC: {0}, Gateway: {1}", m[0].mac, m[0].gatewaymac);
  2807. } else {
  2808. moutput['MAC Layer'] = format("MAC: {0}", m[0].mac);
  2809. }
  2810. moutputCount++;
  2811. }
  2812. moutput['IPv4 Layer'] = '';
  2813. moutput['IPv6 Layer'] = '';
  2814. for (var j = 0; j < m.length; j++) {
  2815. var iplayer = m[j];
  2816. if (iplayer.family == 'IPv4' || iplayer.family == 'IPv6') {
  2817. if (iplayer.gateway && iplayer.netmask) {
  2818. moutput[iplayer.family + ' Layer'] += format("IP: {0}, Mask: {1}, Gateway: {2} ", iplayer.address, iplayer.netmask, iplayer.gateway);
  2819. moutputCount++;
  2820. } else {
  2821. if (iplayer.address) {
  2822. moutput[iplayer.family + ' Layer'] += format("IP: {0} ", iplayer.address);
  2823. moutputCount++;
  2824. }
  2825. }
  2826. }
  2827. }
  2828. if (moutput['IPv4 Layer'] == '') delete moutput['IPv4 Layer'];
  2829. if (moutput['IPv6 Layer'] == '') delete moutput['IPv6 Layer'];
  2830. if (moutputCount > 0) {
  2831. minfo[ifTitle] = moutput;
  2832. info["Networking"] = minfo;
  2833. }
  2834. }
  2835. }
  2836. // Intel AMT
  2837. if (node.intelamt != null) {
  2838. var output = {}, outputCount = 0;
  2839. output["Version"] = (node.intelamt.ver) ? ('v' + node.intelamt.ver) : ('<i>' + "Unknown" + '</i>'); outputCount++;
  2840. var provisioningStates = { 0: "Not Activated (Pre)", 1: "Not Activated (In)", 2: "Activated" };
  2841. var provisioningMode = '';
  2842. if ((node.intelamt.state == 2) && node.intelamt.flags) { if (node.intelamt.flags & 2) { provisioningMode = (', ' + "Client Control Mode (CCM)"); } else if (node.intelamt.flags & 4) { provisioningMode = (', ' + "Admin Control Mode (ACM)"); } }
  2843. output["Provisioning State"] = ((node.intelamt.state) ? (provisioningStates[node.intelamt.state]) : ('<i>' + "Unknown" + '</i>')) + provisioningMode; outputCount++;
  2844. output["Security"] = (node.intelamt.tls == 1) ? "Secured using TLS" : "TLS is not setup"; outputCount++;
  2845. output["Admin Credentials"] = (node.intelamt.user == null || node.intelamt.user == '') ? "Not Known" : "Known"; outputCount++;
  2846. if (outputCount > 0) { info["Intel Active Management Technology (Intel AMT)"] = output; }
  2847. }
  2848. if (hardware != null) {
  2849. if (hardware.identifiers) {
  2850. var output = {}, outputCount = 0, ident = hardware.identifiers;
  2851. // BIOS
  2852. if (ident.bios_vendor) { output["Vendor"] = ident.bios_vendor; outputCount++; }
  2853. if (ident.bios_version) { output["Version"] = ident.bios_version; outputCount++; }
  2854. if (outputCount > 0) { info["BIOS"] = output; }
  2855. output = {}, outputCount = 0;
  2856. // Motherboard
  2857. if (ident.board_vendor) { output["Vendor"] = ident.board_vendor; outputCount++; }
  2858. if (ident.board_name) { output["Name"] = ident.board_name; outputCount++; }
  2859. if (ident.board_serial && (ident.board_serial != '')) { output["Serial"] = ident.board_serial; outputCount++; }
  2860. if (ident.board_version) { output["Version"] = ident.board_version; }
  2861. if (ident.product_uuid) { output["Identifier"] = ident.product_uuid; }
  2862. if (ident.cpu_name) { output["CPU"] = ident.cpu_name; }
  2863. if (ident.gpu_name) { for (var i in ident.gpu_name) { output["GPU" + (parseInt(i) + 1)] = ident.gpu_name[i]; } }
  2864. if (outputCount > 0) { info["Motherboard"] = output; }
  2865. }
  2866. // Memory
  2867. if (hardware.windows) {
  2868. if (hardware.windows.memory) {
  2869. var output = {}, outputCount = 0, minfo = {};
  2870. hardware.windows.memory.sort(function (a, b) { if (a.BankLabel > b.BankLabel) return 1; if (a.BankLabel < b.BankLabel) return -1; return 0; });
  2871. for (var i in hardware.windows.memory) {
  2872. var m = hardware.windows.memory[i], moutput = {}, moutputCount = 0;
  2873. if (m.Capacity) { moutput["Capacity/Speed"] = (m.Capacity / 1024 / 1024) + " Mb, " + m.Speed + " Mhz"; moutputCount++; }
  2874. if (m.PartNumber) { moutput["Part Number"] = ((m.Manufacturer && m.Manufacturer != 'Undefined') ? (m.Manufacturer + ', ') : '') + m.PartNumber; moutputCount++; }
  2875. if (moutputCount > 0) { minfo[m.BankLabel] = moutput; info["Memory"] = minfo; }
  2876. }
  2877. }
  2878. }
  2879. // Storage
  2880. if (hardware.identifiers && ident.storage_devices) {
  2881. var output = {}, outputCount = 0, minfo = {};
  2882. // Sort Storage
  2883. ident.storage_devices.sort(function (a, b) { if (a.Caption > b.Caption) return 1; if (a.Caption < b.Caption) return -1; return 0; });
  2884. for (var i in ident.storage_devices) {
  2885. var m = ident.storage_devices[i], moutput = {};
  2886. if (m.Size) {
  2887. if (m.Model && (m.Model != m.Caption)) { moutput["Model"] = m.Model; outputCount++; }
  2888. if ((typeof m.Size == 'string') && (parseInt(m.Size) == m.Size)) { m.Size = parseInt(m.Size); }
  2889. if (typeof m.Size == 'number') { moutput["Capacity"] = Math.floor(m.Size / 1024 / 1024) + 'Mb'; outputCount++; }
  2890. if (typeof m.Size == 'string') { moutput["Capacity"] = m.Size; outputCount++; }
  2891. if (moutputCount > 0) { minfo[m.Caption] = moutput; info["Storage"] = minfo; }
  2892. }
  2893. }
  2894. }
  2895. }
  2896. // Display everything
  2897. if (args.json) {
  2898. console.log(JSON.stringify(info, ' ', 2));
  2899. } else {
  2900. for (var i in info) {
  2901. console.log('--- ' + i + ' ---');
  2902. for (var j in info[i]) {
  2903. if ((typeof info[i][j] == 'string') || (typeof info[i][j] == 'number')) {
  2904. console.log(' ' + j + ': ' + info[i][j]);
  2905. } else {
  2906. console.log(' ' + j + ':');
  2907. for (var k in info[i][j]) {
  2908. console.log(' ' + k + ': ' + info[i][j][k]);
  2909. }
  2910. }
  2911. }
  2912. }
  2913. }
  2914. }
  2915. // Read the Mesh Agent error log and index it.
  2916. function indexAgentErrorLog() {
  2917. // Index the messages
  2918. const lines = require('fs').readFileSync('../meshcentral-data/agenterrorlogs.txt', { encoding: 'utf8', flag: 'r' }).split('\r\n');
  2919. var errorIndex = {}; // "msg" --> [ { lineNumber, elemenetNumber } ]
  2920. for (var i = 0; i < lines.length; i++) {
  2921. const line = lines[i];
  2922. if (line.length > 88) {
  2923. var nodeid = line.substring(0, 70);
  2924. var fetchTime = parseInt(line.substring(72, 85));
  2925. var data = JSON.parse(line.substring(87));
  2926. if ((data != null) && (data.action == 'errorlog') && (Array.isArray(data.log))) {
  2927. for (var j = 0; j < data.log.length; j++) {
  2928. var entry = data.log[j];
  2929. if ((entry != null) && (typeof entry.t == 'number') && (typeof entry.m == 'string')) {
  2930. const msg = entry.m;
  2931. if (errorIndex[msg] == null) { errorIndex[msg] = []; }
  2932. errorIndex[msg].push({ l: i, e: j });
  2933. }
  2934. }
  2935. }
  2936. }
  2937. }
  2938. // Sort the messages by frequency
  2939. var errorIndexCount = []; // [ { m: "msg", c: count } ]
  2940. for (var i in errorIndex) { errorIndexCount.push({ m: i, c: errorIndex[i].length }); }
  2941. errorIndexCount = errorIndexCount.sort(function (a, b) { return b.c - a.c })
  2942. // Display the results
  2943. for (var i = 0; i < errorIndexCount.length; i++) {
  2944. const m = errorIndexCount[i].m;
  2945. if ((m.indexOf('STUCK') >= 0) || (m.indexOf('FATAL') >= 0)) { console.log(errorIndexCount[i].c, m); }
  2946. }
  2947. }