2022-02-15 04:33:19 +01:00
|
|
|
const logger = require('./logger.js');
|
|
|
|
const spawn = require('child_process').spawn;
|
2022-03-10 12:29:41 +01:00
|
|
|
const sudo = require('sudo');
|
2022-02-15 04:33:19 +01:00
|
|
|
|
2022-03-10 12:29:41 +01:00
|
|
|
async function execute(command, args, useSudo, returnOnClose) {
|
|
|
|
if (command === undefined || command.length === 0) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (returnOnClose === undefined) {
|
|
|
|
returnOnClose = false;
|
|
|
|
}
|
|
|
|
let startTime = new Date().getTime();
|
|
|
|
let resultData = "";
|
|
|
|
let resultError = "";
|
|
|
|
command = command.trim();
|
|
|
|
let process;
|
|
|
|
if (useSudo) {
|
|
|
|
logger.debug('executing sudo command \'' + command + '\' (args: \'' + args + '\')...');
|
|
|
|
args.unshift(command);
|
|
|
|
process = sudo(args, { cachePassword: true, prompt: 'sudo password:' });
|
|
|
|
} else {
|
|
|
|
logger.debug('executing command \'' + command + '\' (args: \'' + args + '\')...');
|
|
|
|
process = spawn(command, args);
|
|
|
|
}
|
|
|
|
process.stdout.on('data', (data) => {
|
|
|
|
resultData += data;
|
|
|
|
});
|
|
|
|
process.stderr.on('data', (data) => {
|
|
|
|
resultError += data;
|
|
|
|
});
|
|
|
|
process.on('spawn', () => {
|
|
|
|
logger.info('spawned command \'' + command + '\' (args: \'' + args + '\')');
|
|
|
|
if (!returnOnClose) {
|
2022-03-03 03:35:34 +01:00
|
|
|
return;
|
|
|
|
}
|
2022-03-10 12:29:41 +01:00
|
|
|
});
|
|
|
|
process.on('error', (err) => {
|
|
|
|
throw new Error(err);
|
|
|
|
});
|
|
|
|
process.on('close', (code) => {
|
|
|
|
let msg = 'command \'' + command + '\' (args: \'' + args + '\') finished with exit code ' + code + ' after ' + (new Date().getTime() - startTime) + 'ms';
|
|
|
|
if (resultData.length > 0) {
|
|
|
|
msg += " > data: " + resultData;
|
2022-02-15 04:33:19 +01:00
|
|
|
}
|
2022-03-10 12:29:41 +01:00
|
|
|
if (resultError.length > 0) {
|
|
|
|
msg += " >>> error: " + resultError;
|
|
|
|
logger.error(msg)
|
|
|
|
return;
|
2022-02-15 04:33:19 +01:00
|
|
|
}
|
2022-03-10 12:29:41 +01:00
|
|
|
logger.debug(msg);
|
|
|
|
if (returnOnClose) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
});
|
2022-02-15 04:33:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
execute
|
|
|
|
}
|