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