Запросить операционную систему удаленного сервера

Я пишу микросервис в Node.js, который запускает определенную операцию командной строки для получения определенной информации. Сервис работает на нескольких серверах, некоторые из них на Linux, некоторые на Windows. Я использую ssh2-exec для подключения к серверам и выполнения команды, однако мне нужен способ определить ОС сервера для запуска правильной команды.

let ssh2Connect = require('ssh2-connect');
let ssh2Exec = require('ssh2-exec');

ssh2Connect(config, function(error, connection) {
    let process = ssh2Exec({
        cmd: '<CHANGE THE COMMAND BASED ON OS>',
        ssh: connection
    });
    //using the results of process...
});

У меня есть идея для решения: после этот вопрос, заранее запустить какую-либо другую команду и определить ОС на основе вывода указанной команды; однако я хочу узнать, есть ли более «формальный» способ добиться этого, в частности, с использованием библиотеки SSH2.


person Rafael Sofi-zada    schedule 17.05.2019    source источник
comment
У вас есть контроль над серверами? Самое простое, что можно сделать, это установить сценарий для конкретной ОС на каждом сервере, чтобы у вашего клиента была команда fixed для запуска независимо от ОС удаленного сервера.   -  person chepner    schedule 14.06.2021


Ответы (1)


Ниже было бы то, как я думаю, что это будет сделано... // Импортируйте модуль ОС, это позволит вам прочитать тип ОС, на котором работает приложение const os = require('os');

//define windows os in string there is only one but for consistency sake we will leave it in an array *if it changes in the future makes it a bit easier to add to an array the remainder of the code doesn't need to change
const winRMOS = ['win32']

//define OS' that need to use ssh protocol *see note above
const sshOS = ['darwin', 'linux', 'freebsd']

// ssh function
const ssh2Connect = (config, function(error, connection) => {
let process = ssh2Exec({
    if (os.platform === 'darwin') {
    cmd: 'Some macOS command'
    },
    if (os.platform === 'linux') {
    cmd: 'Some linux command'
    },
    ssh: connection
 });
 //using the results of process...
 });

 // winrm function there may but some other way to do this but winrm is the way i know how
const winRM2Connect = (config, function(error, connection) => {
let process = ssh2Exec({
    cmd: 'Some Windows command'
    winRM: connection
});
//using the results of process...
});


// if statements to determine which one to use based on the os.platform that is returned.
if (os.platform().includes(sshOS)){
  ssh2Connect(config)
} elseif( os.platform().includes(winrmOS)){
  winrm2Connect(config)
}
person user10135683    schedule 14.06.2021