wmic refactoring (windows codepage issues)

This commit is contained in:
Sebastian Hildebrandt 2021-10-17 17:37:45 +02:00
parent a4bb6f0a02
commit e214f3297c
14 changed files with 10726 additions and 10615 deletions

View File

@ -127,12 +127,12 @@ function parseDarwinAudio(audioObject, id) {
function parseWindowsAudio(lines) {
const result = {};
const status = util.getValue(lines, 'StatusInfo', '=');
// const description = util.getValue(lines, 'Description', '=');
const status = util.getValue(lines, 'StatusInfo', ':');
// const description = util.getValue(lines, 'Description', ':');
result.id = util.getValue(lines, 'DeviceID', '='); // PNPDeviceID??
result.name = util.getValue(lines, 'name', '=');
result.manufacturer = util.getValue(lines, 'manufacturer', '=');
result.id = util.getValue(lines, 'DeviceID', ':'); // PNPDeviceID??
result.name = util.getValue(lines, 'name', ':');
result.manufacturer = util.getValue(lines, 'manufacturer', ':');
result.revision = null;
result.driver = null;
result.default = null;
@ -194,11 +194,11 @@ function audio(callback) {
});
}
if (_windows) {
util.wmic('path Win32_SoundDevice get /value').then((stdout, error) => {
util.powerShell('Get-WmiObject Win32_SoundDevice | fl *').then((stdout, error) => {
if (!error) {
const parts = stdout.toString().split(/\n\s*\n/);
for (let i = 0; i < parts.length; i++) {
if (util.getValue(parts[i].split('\n'), 'name', '=')) {
if (util.getValue(parts[i].split('\n'), 'name', ':')) {
result.push(parseWindowsAudio(parts[i].split('\n')));
}
}

View File

@ -29,7 +29,7 @@ const _sunos = (_platform === 'sunos');
function parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity) {
const result = {};
let status = util.getValue(lines, 'BatteryStatus', '=').trim();
let status = util.getValue(lines, 'BatteryStatus', ':').trim();
// 1 = "Discharging"
// 2 = "On A/C"
// 3 = "Fully Charged"
@ -45,15 +45,15 @@ function parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity) {
const statusValue = status ? parseInt(status) : 0;
result.status = statusValue;
result.hasBattery = true;
result.maxCapacity = fullChargeCapacity || parseInt(util.getValue(lines, 'DesignCapacity', '=') || 0);
result.designedCapacity = parseInt(util.getValue(lines, 'DesignCapacity', '=') || designedCapacity);
result.voltage = parseInt(util.getValue(lines, 'DesignVoltage', '=') || 0) / 1000.0;
result.maxCapacity = fullChargeCapacity || parseInt(util.getValue(lines, 'DesignCapacity', ':') || 0);
result.designedCapacity = parseInt(util.getValue(lines, 'DesignCapacity', ':') || designedCapacity);
result.voltage = parseInt(util.getValue(lines, 'DesignVoltage', ':') || 0) / 1000.0;
result.capacityUnit = 'mWh';
result.percent = parseInt(util.getValue(lines, 'EstimatedChargeRemaining', '=') || 0);
result.percent = parseInt(util.getValue(lines, 'EstimatedChargeRemaining', ':') || 0);
result.currentCapacity = parseInt(result.maxCapacity * result.percent / 100);
result.isCharging = (statusValue >= 6 && statusValue <= 9) || statusValue === 11 || (!(statusValue === 3) && !(statusValue === 1) && result.percent < 100);
result.acConnected = result.isCharging || statusValue === 2;
result.model = util.getValue(lines, 'DeviceID', '=');
result.model = util.getValue(lines, 'DeviceID', ':');
} else {
result.status = -1;
}
@ -225,7 +225,7 @@ module.exports = function (callback) {
if (_windows) {
try {
const workload = [];
workload.push(util.wmic('Path Win32_Battery Get /value'));
workload.push(util.powerShell('Get-WmiObject Win32_Battery | fl *'));
workload.push(util.powerShell('(Get-WmiObject -Class BatteryStaticData -Namespace ROOT/WMI).DesignedCapacity'));
workload.push(util.powerShell('(Get-WmiObject -Class BatteryFullChargedCapacity -Namespace ROOT/WMI).FullChargedCapacity'));
util.promiseAll(
@ -233,7 +233,7 @@ module.exports = function (callback) {
).then(data => {
if (data) {
// let parts = data.results[0].split(/\n\s*\n/);
let parts = data.results[0].split('\r\n');
let parts = data.results[0].split(/\n\s*\n/);
let batteries = [];
const hasValue = value => /\S/.test(value);
for (let i = 0; i < parts.length; i++) {

View File

@ -29,7 +29,7 @@ const _openbsd = (_platform === 'openbsd');
const _netbsd = (_platform === 'netbsd');
const _sunos = (_platform === 'sunos');
function parseBluetoothTyoe(str) {
function parseBluetoothType(str) {
let result = '';
if (str.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
@ -51,7 +51,7 @@ function parseLinuxBluetoothInfo(lines, macAddr1, macAddr2) {
result.macDevice = macAddr1;
result.macHost = macAddr2;
result.batteryPercent = null;
result.type = parseBluetoothTyoe(result.name.toLowerCase());
result.type = parseBluetoothType(result.name.toLowerCase());
result.connected = false;
return result;
@ -67,7 +67,7 @@ function parseDarwinBluetoothDevices(bluetoothObject, macAddr2) {
result.macDevice = (bluetoothObject.device_addr || '').toLowerCase().replace(/-/g, ':');
result.macHost = macAddr2;
result.batteryPercent = bluetoothObject.device_batteryPercent || null;
result.type = parseBluetoothTyoe(typeStr);
result.type = parseBluetoothType(typeStr);
result.connected = bluetoothObject.device_isconnected === 'attrib_Yes' || false;
return result;
@ -77,12 +77,12 @@ function parseWindowsBluetooth(lines) {
const result = {};
result.device = null;
result.name = util.getValue(lines, 'name', '=');
result.manufacturer = util.getValue(lines, 'manufacturer', '=');
result.name = util.getValue(lines, 'name', ':');
result.manufacturer = util.getValue(lines, 'manufacturer', ':');
result.macDevice = null;
result.macHost = null;
result.batteryPercent = null;
result.type = parseBluetoothTyoe(result.name.toLowerCase());
result.type = parseBluetoothType(result.name.toLowerCase());
result.connected = null;
return result;
@ -158,11 +158,11 @@ function bluetoothDevices(callback) {
});
}
if (_windows) {
util.wmic('path Win32_PNPEntity get /value').then((stdout, error) => {
util.powerShell('Get-WmiObject Win32_PNPEntity | fl *').then((stdout, error) => {
if (!error) {
const parts = stdout.toString().split(/\n\s*\n/);
for (let i = 0; i < parts.length; i++) {
if (util.getValue(parts[i].split('\n'), 'PNPClass', '=') === 'Bluetooth') {
if (util.getValue(parts[i].split('\n'), 'PNPClass', ':') === 'Bluetooth') {
result.push(parseWindowsBluetooth(parts[i].split('\n')));
}
}

View File

@ -751,8 +751,8 @@ function getCpu() {
if (_windows) {
try {
const workload = [];
workload.push(util.wmic('cpu get /value'));
workload.push(util.wmic('path Win32_CacheMemory get CacheType,InstalledSize,Purpose'));
workload.push(util.powerShell('Get-WmiObject Win32_processor | fl *'));
workload.push(util.powerShell('Get-WmiObject Win32_CacheMemory | select CacheType,InstalledSize,Purpose | fl *'));
// workload.push(util.powerShell('Get-ComputerInfo -property "HyperV*"'));
workload.push(util.powerShell('(Get-CimInstance Win32_ComputerSystem).HypervisorPresent'));
@ -760,7 +760,7 @@ function getCpu() {
workload
).then(data => {
let lines = data[0].split('\r\n');
let name = util.getValue(lines, 'name', '=') || '';
let name = util.getValue(lines, 'name', ':') || '';
if (name.indexOf('@') >= 0) {
result.brand = name.split('@')[0].trim();
result.speed = name.split('@')[1] ? parseFloat(name.split('@')[1].trim()) : 0;
@ -770,15 +770,15 @@ function getCpu() {
result.speed = 0;
}
result = cpuBrandManufacturer(result);
result.revision = util.getValue(lines, 'revision', '=');
result.revision = util.getValue(lines, 'revision', ':');
result.cache.l1d = 0;
result.cache.l1i = 0;
result.cache.l2 = util.getValue(lines, 'l2cachesize', '=');
result.cache.l3 = util.getValue(lines, 'l3cachesize', '=');
result.cache.l2 = util.getValue(lines, 'l2cachesize', ':');
result.cache.l3 = util.getValue(lines, 'l3cachesize', ':');
if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2, 10) * 1024; }
if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3, 10) * 1024; }
result.vendor = util.getValue(lines, 'manufacturer', '=');
result.speedMax = Math.round(parseFloat(util.getValue(lines, 'maxclockspeed', '=').replace(/,/g, '.')) / 10.0) / 100;
result.vendor = util.getValue(lines, 'manufacturer', ':');
result.speedMax = Math.round(parseFloat(util.getValue(lines, 'maxclockspeed', ':').replace(/,/g, '.')) / 10.0) / 100;
if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
result.speed = getAMDSpeed(result.brand);
}
@ -787,7 +787,7 @@ function getCpu() {
}
result.speedMin = result.speed;
let description = util.getValue(lines, 'description', '=').split(' ');
let description = util.getValue(lines, 'description', ':').split(' ');
for (let i = 0; i < description.length; i++) {
if (description[i].toLowerCase().startsWith('family') && (i + 1) < description.length && description[i + 1]) {
result.family = description[i + 1];
@ -800,14 +800,14 @@ function getCpu() {
}
}
// socket type
const socketId = util.getValue(lines, 'UpgradeMethod', '=');
const socketId = util.getValue(lines, 'UpgradeMethod', ':');
if (socketTypes[socketId]) {
result.socket = socketTypes[socketId];
}
// # threads / # cores
const countProcessors = util.countLines(lines, 'Caption');
const countThreads = util.getValue(lines, 'NumberOfLogicalProcessors', '=');
const countCores = util.getValue(lines, 'NumberOfCores', '=');
const countThreads = util.getValue(lines, 'NumberOfLogicalProcessors', ':');
const countCores = util.getValue(lines, 'NumberOfCores', ':');
if (countProcessors) {
result.processors = parseInt(countProcessors) || 1;
}
@ -819,18 +819,19 @@ function getCpu() {
result.cores = result.cores * countProcessors;
result.physicalCores = result.physicalCores * countProcessors;
}
lines = data[1].split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
lines.forEach(function (line) {
if (line !== '') {
line = line.trim().split(/\s\s+/);
const parts = data[1].split(/\n\s*\n/);;
parts.forEach(function (part) {
lines = part.split('\r\n');
const cacheType = util.getValue(lines, 'CacheType');
const purpose = util.getValue(lines, 'Purpose');
const installedSize = util.getValue(lines, 'InstalledSize');
// L1 Instructions
if (line[2] === 'L1 Cache' && line[0] === '3') {
result.cache.l1i = parseInt(line[1], 10);
if (purpose === 'L1 Cache' && cacheType === '3') {
result.cache.l1i = parseInt(installedSize, 10);
}
// L1 Data
if (line[2] === 'L1 Cache' && line[0] === '4') {
result.cache.l1d = parseInt(line[1], 10);
}
if (purpose === 'L1 Cache' && cacheType === '4') {
result.cache.l1d = parseInt(installedSize, 10);
}
});
// lines = data[2].split('\r\n');
@ -1134,7 +1135,7 @@ function cpuTemperature(callback) {
}
if (_windows) {
try {
util.wmic('/namespace:\\\\root\\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature').then((stdout, error) => {
util.powerShell('Get-WmiObject MSAcpi_ThermalZoneTemperature -Namespace "root/wmi" | Select CurrentTemperature').then((stdout, error) => {
if (!error) {
let sum = 0;
let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
@ -1373,30 +1374,31 @@ function cpuCache(callback) {
}
if (_windows) {
try {
util.wmic('cpu get l2cachesize, l3cachesize /value').then((stdout, error) => {
util.powerShell('Get-WmiObject Win32_processor | fl *').then((stdout, error) => {
if (!error) {
let lines = stdout.split('\r\n');
result.l1d = 0;
result.l1i = 0;
result.l2 = util.getValue(lines, 'l2cachesize', '=');
result.l3 = util.getValue(lines, 'l3cachesize', '=');
result.l2 = util.getValue(lines, 'l2cachesize', ':');
result.l3 = util.getValue(lines, 'l3cachesize', ':');
if (result.l2) { result.l2 = parseInt(result.l2, 10) * 1024; }
if (result.l3) { result.l3 = parseInt(result.l3, 10) * 1024; }
}
util.wmic('path Win32_CacheMemory get CacheType,InstalledSize,Purpose').then((stdout, error) => {
util.powerShell('Get-WmiObject Win32_CacheMemory | select CacheType,InstalledSize,Purpose | fl ').then((stdout, error) => {
if (!error) {
let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
lines.forEach(function (line) {
if (line !== '') {
line = line.trim().split(/\s\s+/);
const parts = data[1].split(/\n\s*\n/);;
parts.forEach(function (part) {
const lines = part.split('\r\n');
const cacheType = util.getValue(lines, 'CacheType');
const purpose = util.getValue(lines, 'Purpose');
const installedSize = util.getValue(lines, 'InstalledSize');
// L1 Instructions
if (line[2] === 'L1 Cache' && line[0] === '3') {
result.l1i = parseInt(line[1], 10);
if (purpose === 'L1 Cache' && cacheType === '3') {
result.l1i = parseInt(installedSize, 10);
}
// L1 Data
if (line[2] === 'L1 Cache' && line[0] === '4') {
result.l1d = parseInt(line[1], 10);
}
if (purpose === 'L1 Cache' && cacheType === '4') {
result.l1d = parseInt(installedSize, 10);
}
});
}

32
lib/filesystem.js Executable file → Normal file
View File

@ -1163,7 +1163,7 @@ function diskLayout(callback) {
if (_windows) {
try {
const workload = [];
workload.push(util.wmic('diskdrive get /value'));
workload.push(util.powerShell('Get-WmiObject Win32_DiskDrive | fl *'));
workload.push(util.powerShell('Get-PhysicalDisk | Format-List'));
if (util.smartMonToolsInstalled()) {
try {
@ -1183,25 +1183,25 @@ function diskLayout(callback) {
let devices = data.results[0].toString().split(/\n\s*\n/);
devices.forEach(function (device) {
let lines = device.split('\r\n');
const size = util.getValue(lines, 'Size', '=').trim();
const status = util.getValue(lines, 'Status', '=').trim().toLowerCase();
const size = util.getValue(lines, 'Size', ':').trim();
const status = util.getValue(lines, 'Status', ':').trim().toLowerCase();
if (size) {
result.push({
device: util.getValue(lines, 'PNPDeviceId', '='),
device: util.getValue(lines, 'PNPDeviceId', ':'),
type: device.indexOf('SSD') > -1 ? 'SSD' : 'HD', // just a starting point ... better: MSFT_PhysicalDisk - Media Type ... see below
name: util.getValue(lines, 'Caption', '='),
vendor: getVendorFromModel(util.getValue(lines, 'Caption', '=', true).trim()),
name: util.getValue(lines, 'Caption', ':'),
vendor: getVendorFromModel(util.getValue(lines, 'Caption', ':', true).trim()),
size: parseInt(size),
bytesPerSector: parseInt(util.getValue(lines, 'BytesPerSector', '=')),
totalCylinders: parseInt(util.getValue(lines, 'TotalCylinders', '=')),
totalHeads: parseInt(util.getValue(lines, 'TotalHeads', '=')),
totalSectors: parseInt(util.getValue(lines, 'TotalSectors', '=')),
totalTracks: parseInt(util.getValue(lines, 'TotalTracks', '=')),
tracksPerCylinder: parseInt(util.getValue(lines, 'TracksPerCylinder', '=')),
sectorsPerTrack: parseInt(util.getValue(lines, 'SectorsPerTrack', '=')),
firmwareRevision: util.getValue(lines, 'FirmwareRevision', '=').trim(),
serialNum: util.getValue(lines, 'SerialNumber', '=').trim(),
interfaceType: util.getValue(lines, 'InterfaceType', '=').trim(),
bytesPerSector: parseInt(util.getValue(lines, 'BytesPerSector', ':')),
totalCylinders: parseInt(util.getValue(lines, 'TotalCylinders', ':')),
totalHeads: parseInt(util.getValue(lines, 'TotalHeads', ':')),
totalSectors: parseInt(util.getValue(lines, 'TotalSectors', ':')),
totalTracks: parseInt(util.getValue(lines, 'TotalTracks', ':')),
tracksPerCylinder: parseInt(util.getValue(lines, 'TracksPerCylinder', ':')),
sectorsPerTrack: parseInt(util.getValue(lines, 'SectorsPerTrack', ':')),
firmwareRevision: util.getValue(lines, 'FirmwareRevision', ':').trim(),
serialNum: util.getValue(lines, 'SerialNumber', ':').trim(),
interfaceType: util.getValue(lines, 'InterfaceType', ':').trim(),
smartStatus: (status === 'ok' ? 'Ok' : (status === 'degraded' ? 'Degraded' : (status === 'pred fail' ? 'Predicted Failure' : 'Unknown'))),
temperature: null,
});

View File

@ -769,9 +769,9 @@ function graphics(callback) {
// https://devblogs.microsoft.com/scripting/use-powershell-to-discover-multi-monitor-information/
try {
const workload = [];
workload.push(util.wmic('path win32_VideoController get /value'));
workload.push(util.powerShell('Get-WmiObject win32_VideoController | fl *'));
workload.push(util.powerShell('gp "HKLM:\\SYSTEM\\ControlSet001\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}\\*" -ErrorAction SilentlyContinue | where MatchingDeviceId $null -NE | select MatchingDeviceId,HardwareInformation.qwMemorySize | fl'));
workload.push(util.wmic('path win32_desktopmonitor get /value'));
workload.push(util.powerShell('Get-WmiObject win32_desktopmonitor | fl *'));
workload.push(util.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorBasicDisplayParams | fl'));
workload.push(util.powerShell('Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Screen]::AllScreens'));
workload.push(util.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorConnectionParams | fl'));
@ -913,7 +913,7 @@ function graphics(callback) {
if ({}.hasOwnProperty.call(sections, i)) {
if (sections[i].trim() !== '') {
let lines = sections[i].trim().split('\r\n');
let pnpDeviceId = util.getValue(lines, 'PNPDeviceID', '=').match(/PCI\\(VEN_[0-9A-F]{4})&amp;(DEV_[0-9A-F]{4})(?:&amp;(SUBSYS_[0-9A-F]{8}))?(?:&amp;(REV_[0-9A-F]{2}))?/i);
let pnpDeviceId = util.getValue(lines, 'PNPDeviceID', ':').match(/PCI\\(VEN_[0-9A-F]{4})&amp;(DEV_[0-9A-F]{4})(?:&amp;(SUBSYS_[0-9A-F]{8}))?(?:&amp;(REV_[0-9A-F]{2}))?/i);
let subDeviceId = null;
let memorySize = null;
if (pnpDeviceId) {
@ -959,17 +959,17 @@ function graphics(callback) {
}
controllers.push({
vendor: util.getValue(lines, 'AdapterCompatibility', '='),
model: util.getValue(lines, 'name', '='),
bus: util.getValue(lines, 'PNPDeviceID', '=').startsWith('PCI') ? 'PCI' : '',
vram: (memorySize == null ? util.toInt(util.getValue(lines, 'AdapterRAM', '=')) : memorySize) / 1024 / 1024,
vramDynamic: (util.getValue(lines, 'VideoMemoryType', '=') === '2'),
vendor: util.getValue(lines, 'AdapterCompatibility', ':'),
model: util.getValue(lines, 'name', ':'),
bus: util.getValue(lines, 'PNPDeviceID', ':').startsWith('PCI') ? 'PCI' : '',
vram: (memorySize == null ? util.toInt(util.getValue(lines, 'AdapterRAM', ':')) : memorySize) / 1024 / 1024,
vramDynamic: (util.getValue(lines, 'VideoMemoryType', ':') === '2'),
subDeviceId
});
_resolutionX = util.toInt(util.getValue(lines, 'CurrentHorizontalResolution', '=')) || _resolutionX;
_resolutionY = util.toInt(util.getValue(lines, 'CurrentVerticalResolution', '=')) || _resolutionY;
_refreshRate = util.toInt(util.getValue(lines, 'CurrentRefreshRate', '=')) || _refreshRate;
_pixelDepth = util.toInt(util.getValue(lines, 'CurrentBitsPerPixel', '=')) || _pixelDepth;
_resolutionX = util.toInt(util.getValue(lines, 'CurrentHorizontalResolution', ':')) || _resolutionX;
_resolutionY = util.toInt(util.getValue(lines, 'CurrentVerticalResolution', ':')) || _resolutionY;
_refreshRate = util.toInt(util.getValue(lines, 'CurrentRefreshRate', ':')) || _refreshRate;
_pixelDepth = util.toInt(util.getValue(lines, 'CurrentBitsPerPixel', ':')) || _pixelDepth;
}
}
}
@ -985,11 +985,11 @@ function graphics(callback) {
let resolutionY = 0;
if (dsections && dsections.length) {
let linesDisplay = dsections[0].split(os.EOL);
vendor = util.getValue(linesDisplay, 'MonitorManufacturer', '=');
model = util.getValue(linesDisplay, 'Name', '=');
deviceID = util.getValue(linesDisplay, 'PNPDeviceID', '=').replace(/&amp;/g, '&').toLowerCase();
resolutionX = util.toInt(util.getValue(linesDisplay, 'ScreenWidth', '='));
resolutionY = util.toInt(util.getValue(linesDisplay, 'ScreenHeight', '='));
vendor = util.getValue(linesDisplay, 'MonitorManufacturer', ':');
model = util.getValue(linesDisplay, 'Name', ':');
deviceID = util.getValue(linesDisplay, 'PNPDeviceID', ':').replace(/&amp;/g, '&').toLowerCase();
resolutionX = util.toInt(util.getValue(linesDisplay, 'ScreenWidth', ':'));
resolutionY = util.toInt(util.getValue(linesDisplay, 'ScreenHeight', ':'));
}
for (let i = 0; i < ssections.length; i++) {
if (ssections[i].trim() !== '') {
@ -1027,15 +1027,15 @@ function graphics(callback) {
main: primary.toLowerCase() === 'true',
builtin: videoOutputTechnology === '2147483648',
connection: videoOutputTechnology && videoTypes[videoOutputTechnology] ? videoTypes[videoOutputTechnology] : '',
resolutionX: util.toInt(util.getValue(bounds, 'Width', '=')),
resolutionY: util.toInt(util.getValue(bounds, 'Height', '=')),
resolutionX: util.toInt(util.getValue(bounds, 'Width', ':')),
resolutionY: util.toInt(util.getValue(bounds, 'Height', ':')),
sizeX: sizeX ? parseInt(sizeX, 10) : null,
sizeY: sizeY ? parseInt(sizeY, 10) : null,
pixelDepth: bitsPerPixel,
currentResX: util.toInt(util.getValue(bounds, 'Width', '=')),
currentResY: util.toInt(util.getValue(bounds, 'Height', '=')),
positionX: util.toInt(util.getValue(bounds, 'X', '=')),
positionY: util.toInt(util.getValue(bounds, 'Y', '=')),
currentResX: util.toInt(util.getValue(bounds, 'Width', ':')),
currentResY: util.toInt(util.getValue(bounds, 'Height', ':')),
positionX: util.toInt(util.getValue(bounds, 'X', ':')),
positionY: util.toInt(util.getValue(bounds, 'Y', ':')),
});
}
}

View File

@ -256,14 +256,14 @@ function mem(callback) {
let swaptotal = 0;
let swapused = 0;
try {
util.wmic('pagefile get AllocatedBaseSize, CurrentUsage').then((stdout, error) => {
util.powerShell('Get-CimInstance Win32_PageFileUsage | Select AllocatedBaseSize, CurrentUsage').then((stdout, error) => {
if (!error) {
let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
lines.forEach(function (line) {
if (line !== '') {
line = line.trim().split(/\s\s+/);
swaptotal = swaptotal + parseInt(line[0], 10);
swapused = swapused + parseInt(line[1], 10);
swaptotal = swaptotal + (parseInt(line[0], 10) || 0);
swapused = swapused + (parseInt(line[1], 10) || 0);
}
});
}
@ -497,28 +497,31 @@ function memLayout(callback) {
const FormFactors = 'Unknown|Other|SIP|DIP|ZIP|SOJ|Proprietary|SIMM|DIMM|TSOP|PGA|RIMM|SODIMM|SRIMM|SMD|SSMP|QFP|TQFP|SOIC|LCC|PLCC|BGA|FPBGA|LGA'.split('|');
try {
util.wmic('memorychip get /value').then((stdout, error) => {
util.powerShell('Get-WmiObject Win32_PhysicalMemory | fl *').then((stdout, error) => {
if (!error) {
let devices = stdout.toString().split('BankL');
let devices = stdout.toString().split(/\n\s*\n/);
devices.shift();
devices.forEach(function (device) {
let lines = device.split('\r\n');
const dataWidth = util.toInt(util.getValue(lines, 'DataWidth', '='));
const totalWidth = util.toInt(util.getValue(lines, 'TotalWidth', '='));
const dataWidth = util.toInt(util.getValue(lines, 'DataWidth', ':'));
const totalWidth = util.toInt(util.getValue(lines, 'TotalWidth', ':'));
const size = parseInt(util.getValue(lines, 'Capacity', ':'), 10) || 0;
if (size) {
result.push({
size: parseInt(util.getValue(lines, 'Capacity', '='), 10) || 0,
bank: util.getValue(lines, 'abel', '='), // BankLabel
type: memoryTypes[parseInt(util.getValue(lines, 'MemoryType', '='), 10) || parseInt(util.getValue(lines, 'SMBIOSMemoryType', '='), 10)],
size,
bank: util.getValue(lines, 'BankLabel', ':'), // BankLabel
type: memoryTypes[parseInt(util.getValue(lines, 'MemoryType', ':'), 10) || parseInt(util.getValue(lines, 'SMBIOSMemoryType', ':'), 10)],
ecc: dataWidth && totalWidth ? totalWidth > dataWidth : false,
clockSpeed: parseInt(util.getValue(lines, 'ConfiguredClockSpeed', '='), 10) || parseInt(util.getValue(lines, 'Speed', '='), 10) || 0,
formFactor: FormFactors[parseInt(util.getValue(lines, 'FormFactor', '='), 10) || 0],
manufacturer: util.getValue(lines, 'Manufacturer', '='),
partNum: util.getValue(lines, 'PartNumber', '='),
serialNum: util.getValue(lines, 'SerialNumber', '='),
voltageConfigured: (parseInt(util.getValue(lines, 'ConfiguredVoltage', '='), 10) || 0) / 1000.0,
voltageMin: (parseInt(util.getValue(lines, 'MinVoltage', '='), 10) || 0) / 1000.0,
voltageMax: (parseInt(util.getValue(lines, 'MaxVoltage', '='), 10) || 0) / 1000.0,
clockSpeed: parseInt(util.getValue(lines, 'ConfiguredClockSpeed', ':'), 10) || parseInt(util.getValue(lines, 'Speed', ':'), 10) || 0,
formFactor: FormFactors[parseInt(util.getValue(lines, 'FormFactor', ':'), 10) || 0],
manufacturer: util.getValue(lines, 'Manufacturer', ':'),
partNum: util.getValue(lines, 'PartNumber', ':'),
serialNum: util.getValue(lines, 'SerialNumber', ':'),
voltageConfigured: (parseInt(util.getValue(lines, 'ConfiguredVoltage', ':'), 10) || 0) / 1000.0,
voltageMin: (parseInt(util.getValue(lines, 'MinVoltage', ':'), 10) || 0) / 1000.0,
voltageMax: (parseInt(util.getValue(lines, 'MaxVoltage', ':'), 10) || 0) / 1000.0,
});
}
});
}
if (callback) { callback(result); }

View File

@ -1048,13 +1048,13 @@ function networkStatsSingle(iface) {
if (sections[i].trim() !== '') {
let lines = sections[i].trim().split('\r\n');
perfData.push({
name: util.getValue(lines, 'Name', '=').replace(/[()[\] ]+/g, '').replace('#', '_').toLowerCase(),
rx_bytes: parseInt(util.getValue(lines, 'BytesReceivedPersec', '='), 10),
rx_errors: parseInt(util.getValue(lines, 'PacketsReceivedErrors', '='), 10),
rx_dropped: parseInt(util.getValue(lines, 'PacketsReceivedDiscarded', '='), 10),
tx_bytes: parseInt(util.getValue(lines, 'BytesSentPersec', '='), 10),
tx_errors: parseInt(util.getValue(lines, 'PacketsOutboundErrors', '='), 10),
tx_dropped: parseInt(util.getValue(lines, 'PacketsOutboundDiscarded', '='), 10)
name: util.getValue(lines, 'Name', ':').replace(/[()[\] ]+/g, '').replace('#', '_').toLowerCase(),
rx_bytes: parseInt(util.getValue(lines, 'BytesReceivedPersec', ':'), 10),
rx_errors: parseInt(util.getValue(lines, 'PacketsReceivedErrors', ':'), 10),
rx_dropped: parseInt(util.getValue(lines, 'PacketsReceivedDiscarded', ':'), 10),
tx_bytes: parseInt(util.getValue(lines, 'BytesSentPersec', ':'), 10),
tx_errors: parseInt(util.getValue(lines, 'PacketsOutboundErrors', ':'), 10),
tx_dropped: parseInt(util.getValue(lines, 'PacketsOutboundDiscarded', ':'), 10)
});
}
}
@ -1182,7 +1182,7 @@ function networkStatsSingle(iface) {
let ifaceName = ifaceSanitized;
// Performance Data
util.wmic('path Win32_PerfRawData_Tcpip_NetworkInterface Get name,BytesReceivedPersec,BytesSentPersec,BytesTotalPersec,PacketsOutboundDiscarded,PacketsOutboundErrors,PacketsReceivedDiscarded,PacketsReceivedErrors /value').then((stdout, error) => {
util.powerShell('Get-WmiObject Win32_PerfRawData_Tcpip_NetworkInterface | fl *').then((stdout, error) => {
if (!error) {
const psections = stdout.toString().split(/\n\s*\n/);
perfData = parseLinesWindowsPerfData(psections);

View File

@ -322,7 +322,7 @@ function osInfo(callback) {
result.release = result.kernel;
try {
const workload = [];
workload.push(util.wmic('os get /value'));
workload.push(util.powerShell('Get-WmiObject Win32_OperatingSystem | fl *'));
// workload.push(execPromise('systeminfo', util.execOptsWin));
// workload.push(util.powerShell('Get-ComputerInfo -property "HyperV*"'));
workload.push(util.powerShell('(Get-CimInstance Win32_ComputerSystem).HypervisorPresent'));
@ -331,10 +331,10 @@ function osInfo(callback) {
workload
).then(data => {
let lines = data.results[0] ? data.results[0].toString().split('\r\n') : [''];
result.distro = util.getValue(lines, 'Caption', '=').trim();
result.serial = util.getValue(lines, 'SerialNumber', '=').trim();
result.build = util.getValue(lines, 'BuildNumber', '=').trim();
result.servicepack = util.getValue(lines, 'ServicePackMajorVersion', '=').trim() + '.' + util.getValue(lines, 'ServicePackMinorVersion', '=').trim();
result.distro = util.getValue(lines, 'Caption', ':').trim();
result.serial = util.getValue(lines, 'SerialNumber', ':').trim();
result.build = util.getValue(lines, 'BuildNumber', ':').trim();
result.servicepack = util.getValue(lines, 'ServicePackMajorVersion', ':').trim() + '.' + util.getValue(lines, 'ServicePackMinorVersion', ':').trim();
result.codepage = util.getCodepage();
// const systeminfo = data.results[1] ? data.results[1].toString() : '';
// result.hypervisor = (systeminfo.indexOf('hypervisor has been detected') !== -1) || (systeminfo.indexOf('ein Hypervisor erkannt') !== -1) || (systeminfo.indexOf('Un hyperviseur a ') !== -1);
@ -737,12 +737,12 @@ function versions(apps, callback) {
});
} else {
if (_windows) {
util.wmic('service get /value').then((stdout) => {
util.powerShell('Get-WmiObject Win32_Service | fl *').then((stdout) => {
let serviceSections = stdout.split(/\n\s*\n/);
for (let i = 0; i < serviceSections.length; i++) {
if (serviceSections[i].trim() !== '') {
let lines = serviceSections[i].trim().split('\r\n');
let srvCaption = util.getValue(lines, 'caption', '=', true).toLowerCase();
let srvCaption = util.getValue(lines, 'caption', ':', true).toLowerCase();
if (srvCaption.indexOf('postgresql') > -1) {
const parts = srvCaption.split(' server ');
if (parts.length > 1) {
@ -1132,10 +1132,10 @@ echo -n "hardware: "; sysctl -n kern.hostuuid; echo;`;
exec(`${sysdir}\\reg query "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid`, util.execOptsWin, function (error, stdout) {
parts = stdout.toString().split('\n\r')[0].split('REG_SZ');
result.os = parts.length > 1 ? parts[1].replace(/\r+|\n+|\s+/ig, '').toLowerCase() : '';
util.wmic('csproduct get /value').then((stdout) => {
util.powerShell('Get-WmiObject Win32_ComputerSystemProduct | fl *').then((stdout) => {
// let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0)[0].trim().split(/\s\s+/);
let lines = stdout.split('\r\n');
result.hardware = util.getValue(lines, 'uuid', '=').toLowerCase();
result.hardware = util.getValue(lines, 'uuid', ':').toLowerCase();
if (callback) {
callback(result);
}

View File

@ -98,17 +98,17 @@ function parseDarwinPrinters(printerObject, id) {
function parseWindowsPrinters(lines, id) {
const result = {};
const status = parseInt(util.getValue(lines, 'PrinterStatus', '='), 10);
const status = parseInt(util.getValue(lines, 'PrinterStatus', ':'), 10);
result.id = id;
result.name = util.getValue(lines, 'name', '=');
result.model = util.getValue(lines, 'DriverName', '=');
result.name = util.getValue(lines, 'name', ':');
result.model = util.getValue(lines, 'DriverName', ':');
result.uri = null;
result.uuid = null;
result.status = winPrinterStatus[status] ? winPrinterStatus[status] : null;
result.local = util.getValue(lines, 'Local', '=') === 'TRUE';
result.default = util.getValue(lines, 'Default', '=') === 'TRUE';
result.shared = util.getValue(lines, 'Shared', '=') === 'TRUE';
result.local = util.getValue(lines, 'Local', ':').toUpperCase() === 'TRUE';
result.default = util.getValue(lines, 'Default', ':').toUpperCase() === 'TRUE';
result.shared = util.getValue(lines, 'Shared', ':').toUpperCase() === 'TRUE';
return result;
}
@ -186,7 +186,7 @@ function printer(callback) {
});
}
if (_windows) {
util.wmic('printer get /value').then((stdout, error) => {
util.powerShell('Get-WmiObject Win32_Printer | fl *').then((stdout, error) => {
if (!error) {
const parts = stdout.toString().split(/\n\s*\n/);
for (let i = 0; i < parts.length; i++) {

View File

@ -324,17 +324,17 @@ function services(srv, callback) {
}
if (_windows) {
try {
util.wmic('service get /value').then((stdout, error) => {
util.powerShell('Get-WmiObject Win32_Service | fl *').then((stdout, error) => {
if (!error) {
let serviceSections = stdout.split(/\n\s*\n/);
for (let i = 0; i < serviceSections.length; i++) {
if (serviceSections[i].trim() !== '') {
let lines = serviceSections[i].trim().split('\r\n');
let srvName = util.getValue(lines, 'Name', '=', true).toLowerCase();
let srvCaption = util.getValue(lines, 'Caption', '=', true).toLowerCase();
let started = util.getValue(lines, 'Started', '=', true);
let startMode = util.getValue(lines, 'StartMode', '=', true);
let pid = util.getValue(lines, 'ProcessId', '=', true);
let srvName = util.getValue(lines, 'Name', ':', true).toLowerCase();
let srvCaption = util.getValue(lines, 'Caption', ':', true).toLowerCase();
let started = util.getValue(lines, 'Started', ':', true);
let startMode = util.getValue(lines, 'StartMode', ':', true);
let pid = util.getValue(lines, 'ProcessId', ':', true);
if (srvString === '*' || srvs.indexOf(srvName) >= 0 || srvs.indexOf(srvCaption) >= 0) {
result.push({
name: srvName,
@ -788,7 +788,7 @@ function processes(callback) {
});
} else if (_windows) {
try {
util.wmic('process get /value').then((stdout, error) => {
util.powerShell('Get-WmiObject Win32_Process | fl *').then((stdout, error) => {
if (!error) {
let processSections = stdout.split(/\n\s*\n/);
let procs = [];
@ -799,15 +799,15 @@ function processes(callback) {
for (let i = 0; i < processSections.length; i++) {
if (processSections[i].trim() !== '') {
let lines = processSections[i].trim().split('\r\n');
let pid = parseInt(util.getValue(lines, 'ProcessId', '=', true), 10);
let parentPid = parseInt(util.getValue(lines, 'ParentProcessId', '=', true), 10);
let statusValue = util.getValue(lines, 'ExecutionState', '=');
let name = util.getValue(lines, 'Caption', '=', true);
let commandLine = util.getValue(lines, 'CommandLine', '=', true);
let commandPath = util.getValue(lines, 'ExecutablePath', '=', true);
let utime = parseInt(util.getValue(lines, 'UserModeTime', '=', true), 10);
let stime = parseInt(util.getValue(lines, 'KernelModeTime', '=', true), 10);
let memw = parseInt(util.getValue(lines, 'WorkingSetSize', '=', true), 10);
let pid = parseInt(util.getValue(lines, 'ProcessId', ':', true), 10);
let parentPid = parseInt(util.getValue(lines, 'ParentProcessId', ':', true), 10);
let statusValue = util.getValue(lines, 'ExecutionState', ':');
let name = util.getValue(lines, 'Caption', ':', true);
let commandLine = util.getValue(lines, 'CommandLine', ':', true);
let commandPath = util.getValue(lines, 'ExecutablePath', ':', true);
let utime = parseInt(util.getValue(lines, 'UserModeTime', ':', true), 10);
let stime = parseInt(util.getValue(lines, 'KernelModeTime', ':', true), 10);
let memw = parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10);
allcpuu = allcpuu + utime;
allcpus = allcpus + stime;
result.all++;
@ -831,11 +831,11 @@ function processes(callback) {
cpuu: 0,
cpus: 0,
mem: memw / os.totalmem() * 100,
priority: parseInt(util.getValue(lines, 'Priority', '=', true), 10),
memVsz: parseInt(util.getValue(lines, 'PageFileUsage', '=', true), 10),
memRss: Math.floor(parseInt(util.getValue(lines, 'WorkingSetSize', '=', true), 10) / 1024),
priority: parseInt(util.getValue(lines, 'Priority', ':', true), 10),
memVsz: parseInt(util.getValue(lines, 'PageFileUsage', ':', true), 10),
memRss: Math.floor(parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10) / 1024),
nice: 0,
started: parseTimeWin(util.getValue(lines, 'CreationDate', '=', true)),
started: parseTimeWin(util.getValue(lines, 'CreationDate', ':', true)),
state: (!statusValue ? _winStatusValues[0] : _winStatusValues[statusValue]),
tty: '',
user: '',
@ -956,7 +956,7 @@ function processLoad(proc, callback) {
if (procSanitized && processes.length && processes[0] !== '------') {
if (_windows) {
try {
util.wmic('process get /value').then((stdout, error) => {
util.powerShell('Get-WmiObject Win32_Process | fl *').then((stdout, error) => {
if (!error) {
let processSections = stdout.split(/\n\s*\n/);
let procStats = [];
@ -968,11 +968,11 @@ function processLoad(proc, callback) {
for (let i = 0; i < processSections.length; i++) {
if (processSections[i].trim() !== '') {
let lines = processSections[i].trim().split('\r\n');
let pid = parseInt(util.getValue(lines, 'ProcessId', '=', true), 10);
let name = util.getValue(lines, 'Caption', '=', true);
let utime = parseInt(util.getValue(lines, 'UserModeTime', '=', true), 10);
let stime = parseInt(util.getValue(lines, 'KernelModeTime', '=', true), 10);
let mem = parseInt(util.getValue(lines, 'WorkingSetSize', '=', true), 10);
let pid = parseInt(util.getValue(lines, 'ProcessId', ':', true), 10);
let name = util.getValue(lines, 'Caption', ':', true);
let utime = parseInt(util.getValue(lines, 'UserModeTime', ':', true), 10);
let stime = parseInt(util.getValue(lines, 'KernelModeTime', ':', true), 10);
let mem = parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10);
allcpuu = allcpuu + utime;
allcpus = allcpus + stime;

View File

@ -343,15 +343,15 @@ function system(callback) {
}
if (_windows) {
try {
util.wmic('csproduct get /value').then((stdout, error) => {
util.powerShell('Get-WmiObject Win32_ComputerSystemProduct | fl *').then((stdout, error) => {
if (!error) {
// let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0)[0].trim().split(/\s\s+/);
let lines = stdout.split('\r\n');
result.manufacturer = util.getValue(lines, 'vendor', '=');
result.model = util.getValue(lines, 'name', '=');
result.version = util.getValue(lines, 'version', '=');
result.serial = util.getValue(lines, 'identifyingnumber', '=');
result.uuid = util.getValue(lines, 'uuid', '=').toLowerCase();
result.manufacturer = util.getValue(lines, 'vendor', ':');
result.model = util.getValue(lines, 'name', ':');
result.version = util.getValue(lines, 'version', ':');
result.serial = util.getValue(lines, 'identifyingnumber', ':');
result.uuid = util.getValue(lines, 'uuid', ':').toLowerCase();
// detect virtual (1)
if (result.model.toLowerCase() === 'virtualbox' || result.model.toLowerCase() === 'kvm' || result.model.toLowerCase() === 'virtual machine' || result.model.toLowerCase() === 'bochs' || result.model.toLowerCase().startsWith('vmware')) {
result.virtual = true;
@ -384,7 +384,7 @@ function system(callback) {
util.wmic('/namespace:\\\\root\\wmi path MS_SystemInformation get /value').then((stdout, error) => {
if (!error) {
let lines = stdout.split('\r\n');
result.sku = util.getValue(lines, 'systemsku', '=');
result.sku = util.getValue(lines, 'systemsku', ':');
}
if (!result.virtual) {
util.wmic('bios get Version, SerialNumber, SMBIOSBIOSVersion').then((stdout, error) => {

View File

@ -197,18 +197,18 @@ function getWindowsUsbTypeCreation(creationclass, name) {
}
function parseWindowsUsb(lines, id) {
const usbType = getWindowsUsbTypeCreation(util.getValue(lines, 'CreationClassName', '=').toLowerCase(), util.getValue(lines, 'name', '=').toLowerCase());
const usbType = getWindowsUsbTypeCreation(util.getValue(lines, 'CreationClassName', ':').toLowerCase(), util.getValue(lines, 'name', ':').toLowerCase());
if (usbType) {
const result = {};
result.bus = null;
result.deviceId = util.getValue(lines, 'deviceid', '=');
result.deviceId = util.getValue(lines, 'deviceid', ':');
result.id = id;
result.name = util.getValue(lines, 'name', '=');
result.name = util.getValue(lines, 'name', ':');
result.type = usbType;
result.removable = null;
result.vendor = null;
result.manufacturer = util.getValue(lines, 'Manufacturer', '=');
result.manufacturer = util.getValue(lines, 'Manufacturer', ':');
result.maxPower = null;
result.serialNumber = null;
@ -263,7 +263,7 @@ function usb(callback) {
});
}
if (_windows) {
util.wmic('Path CIM_LogicalDevice where "Description like \'USB%\'" get /value').then((stdout, error) => {
util.powerShell('Get-WmiObject CIM_LogicalDevice | where { $_.Description -match "^USB"}').then((stdout, error) => {
if (!error) {
const parts = stdout.toString().split(/\n\s*\n/);
for (let i = 0; i < parts.length; i++) {

View File

@ -26,43 +26,43 @@ const _openbsd = (_platform === 'openbsd');
const _netbsd = (_platform === 'netbsd');
const _sunos = (_platform === 'sunos');
let _winDateFormat = {
dateFormat: '',
dateSeperator: '',
timeFormat: '',
timeSeperator: '',
amDesignator: '',
pmDesignator: ''
};
// let _winDateFormat = {
// dateFormat: '',
// dateSeperator: '',
// timeFormat: '',
// timeSeperator: '',
// amDesignator: '',
// pmDesignator: ''
// };
// --------------------------
// array of users online = sessions
function getWinCulture() {
return new Promise((resolve) => {
process.nextTick(() => {
if (!_winDateFormat.dateFormat) {
util.powerShell('(get-culture).DateTimeFormat')
.then(data => {
let lines = data.toString().split('\r\n');
_winDateFormat.dateFormat = util.getValue(lines, 'ShortDatePattern', ':');
_winDateFormat.dateSeperator = util.getValue(lines, 'DateSeparator', ':');
_winDateFormat.timeFormat = util.getValue(lines, 'ShortTimePattern', ':');
_winDateFormat.timeSeperator = util.getValue(lines, 'TimeSeparator', ':');
_winDateFormat.amDesignator = util.getValue(lines, 'AMDesignator', ':');
_winDateFormat.pmDesignator = util.getValue(lines, 'PMDesignator', ':');
// function getWinCulture() {
// return new Promise((resolve) => {
// process.nextTick(() => {
// if (!_winDateFormat.dateFormat) {
// util.powerShell('(get-culture).DateTimeFormat')
// .then(data => {
// let lines = data.toString().split('\r\n');
// _winDateFormat.dateFormat = util.getValue(lines, 'ShortDatePattern', ':');
// _winDateFormat.dateSeperator = util.getValue(lines, 'DateSeparator', ':');
// _winDateFormat.timeFormat = util.getValue(lines, 'ShortTimePattern', ':');
// _winDateFormat.timeSeperator = util.getValue(lines, 'TimeSeparator', ':');
// _winDateFormat.amDesignator = util.getValue(lines, 'AMDesignator', ':');
// _winDateFormat.pmDesignator = util.getValue(lines, 'PMDesignator', ':');
resolve(_winDateFormat);
})
.catch(() => {
resolve(_winDateFormat);
});
} else {
resolve(_winDateFormat);
}
});
});
}
// resolve(_winDateFormat);
// })
// .catch(() => {
// resolve(_winDateFormat);
// });
// } else {
// resolve(_winDateFormat);
// }
// });
// });
// }
function parseUsersLinux(lines, phase) {
let result = [];
@ -176,43 +176,43 @@ function parseUsersDarwin(lines) {
return result;
}
function parseUsersWin(lines, culture) {
// function parseUsersWin(lines, culture) {
let result = [];
const header = lines[0];
const headerDelimiter = [];
if (header) {
const start = (header[0] === ' ') ? 1 : 0;
headerDelimiter.push(start - 1);
let nextSpace = 0;
for (let i = start + 1; i < header.length; i++) {
if (header[i] === ' ' && ((header[i - 1] === ' ') || (header[i - 1] === '.'))) {
nextSpace = i;
} else {
if (nextSpace) {
headerDelimiter.push(nextSpace);
nextSpace = 0;
}
}
}
for (let i = 1; i < lines.length; i++) {
if (lines[i].trim()) {
const user = lines[i].substring(headerDelimiter[0] + 1, headerDelimiter[1]).trim() || '';
const tty = lines[i].substring(headerDelimiter[1] + 1, headerDelimiter[2] - 2).trim() || '';
const dateTime = util.parseDateTime(lines[i].substring(headerDelimiter[5] + 1, 2000).trim(), culture) || '';
result.push({
user: user,
tty: tty,
date: dateTime.date,
time: dateTime.time,
ip: '',
command: ''
});
}
}
}
return result;
}
// let result = [];
// const header = lines[0];
// const headerDelimiter = [];
// if (header) {
// const start = (header[0] === ' ') ? 1 : 0;
// headerDelimiter.push(start - 1);
// let nextSpace = 0;
// for (let i = start + 1; i < header.length; i++) {
// if (header[i] === ' ' && ((header[i - 1] === ' ') || (header[i - 1] === '.'))) {
// nextSpace = i;
// } else {
// if (nextSpace) {
// headerDelimiter.push(nextSpace);
// nextSpace = 0;
// }
// }
// }
// for (let i = 1; i < lines.length; i++) {
// if (lines[i].trim()) {
// const user = lines[i].substring(headerDelimiter[0] + 1, headerDelimiter[1]).trim() || '';
// const tty = lines[i].substring(headerDelimiter[1] + 1, headerDelimiter[2] - 2).trim() || '';
// const dateTime = util.parseDateTime(lines[i].substring(headerDelimiter[5] + 1, 2000).trim(), culture) || '';
// result.push({
// user: user,
// tty: tty,
// date: dateTime.date,
// time: dateTime.time,
// ip: '',
// command: ''
// });
// }
// }
// }
// return result;
// }
function users(callback) {
@ -283,21 +283,62 @@ function users(callback) {
}
if (_windows) {
try {
util.powerShell('query user').then(stdout => {
if (stdout) {
// lines / split
let lines = stdout.toString().split('\r\n');
getWinCulture()
.then(culture => {
result = parseUsersWin(lines, culture);
if (callback) { callback(result); }
resolve(result);
});
} else {
if (callback) { callback(result); }
resolve(result);
const workload = [];
// workload.push(util.powerShell('Get-CimInstance -ClassName Win32_Account | fl *'));
workload.push(util.powerShell('Get-WmiObject Win32_LogonSession | fl *'));
workload.push(util.powerShell('Get-WmiObject Win32_LoggedOnUser | fl *'));
workload.push(util.powerShell('Get-WmiObject Win32_Process -Filter "name=\'explorer.exe\'" | Select @{Name="domain";Expression={$_.GetOwner().Domain}}, @{Name="username";Expression={$_.GetOwner().User}} | fl'));
Promise.all(
workload
).then(data => {
// controller + vram
// let accounts = parseWinAccounts(data[0].split(/\n\s*\n/));
let sessions = parseWinSessions(data[0].split(/\n\s*\n/));
let loggedons = parseWinLoggedOn(data[1].split(/\n\s*\n/));
let users = parseWinUsers(data[2].split(/\n\s*\n/));
for (let id in loggedons) {
if ({}.hasOwnProperty.call(loggedons, id)) {
loggedons[id].dateTime = {}.hasOwnProperty.call(sessions, id) ? sessions[id] : '';
}
}
users.forEach(user => {
let dateTime = '';
for (let id in loggedons) {
if ({}.hasOwnProperty.call(loggedons, id)) {
if (loggedons[id].user === user.user && (!dateTime || dateTime < loggedons[id].dateTime)) {
dateTime = loggedons[id].dateTime;
}
}
}
result.push({
user: user.user,
tty: '',
date: `${dateTime.substr(0, 4)}-${dateTime.substr(4, 2)}-${dateTime.substr(6, 2)}`,
time: `${dateTime.substr(8, 2)}:${dateTime.substr(10, 2)}`,
ip: '',
command: ''
});
});
if (callback) { callback(result); }
resolve(result);
});
// util.powerShell('query user').then(stdout => {
// if (stdout) {
// // lines / split
// let lines = stdout.toString().split('\r\n');
// getWinCulture()
// .then(culture => {
// result = parseUsersWin(lines, culture);
// if (callback) { callback(result); }
// resolve(result);
// });
// } else {
// if (callback) { callback(result); }
// resolve(result);
// }
// });
} catch (e) {
if (callback) { callback(result); }
resolve(result);
@ -308,4 +349,69 @@ function users(callback) {
});
}
// function parseWinAccounts(accountParts) {
// const accounts = [];
// accountParts.forEach(account => {
// const lines = account.split('\r\n');
// const name = util.getValue(lines, 'name', ':', true);
// const domain = util.getValue(lines, 'domain', ':', true);
// accounts.push(`${domain}\${name}`);
// });
// return accounts;
// }
function parseWinSessions(sessionParts) {
const sessions = {};
sessionParts.forEach(session => {
const lines = session.split('\r\n');
const id = util.getValue(lines, 'LogonId');
const starttime = util.getValue(lines, 'starttime');
if (id) {
sessions[id] = starttime;
}
});
return sessions;
}
function parseWinUsers(userParts) {
const users = [];
userParts.forEach(user => {
const lines = user.split('\r\n');
const domain = util.getValue(lines, 'domain', ':', true);
const username = util.getValue(lines, 'username', ':', true);
if (username) {
users.push({
domain,
user: username
});
}
});
return users;
}
function parseWinLoggedOn(loggedonParts) {
const loggedons = {};
loggedonParts.forEach(loggedon => {
const lines = loggedon.split('\r\n');
const antecendent = util.getValue(lines, 'antecedent', ':', true);
let parts = antecendent.split(',');
const domainParts = parts.length > 1 ? parts[0].split('=') : [];
const nameParts = parts.length > 1 ? parts[1].split('=') : [];
const domain = domainParts.length > 1 ? domainParts[1].replace(/"/g, '') : '';
const name = nameParts.length > 1 ? nameParts[1].replace(/"/g, '') : '';
const dependent = util.getValue(lines, 'dependent', ':', true);
parts = dependent.split('=');
const id = parts.length > 1 ? parts[1].replace(/"/g, '') : '';
if (id) {
loggedons[id] = {
domain,
user: name
};
}
});
return loggedons;
}
exports.users = users;