首页 > 解决方案 > Query a remote server's operating system

问题描述

I'm writing a microservice in Node.js, that runs a particular command line operation to get a specific piece of information. The service runs on multiple server, some of them on Linux, some on Windows. I'm using ssh2-exec to connect to the servers and execute a command, however, I need a way of determining the server's OS to run the correct command.

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...
});

I have an idea for the solution: following this question, run some other command beforehand, and determine the OS from the output of said command; however, I want to learn if there's a more "formal" way of achieving this, specifically using SSH2 library.

标签: node.jsshellsshssh2-sftpssh2-exec

解决方案


下面将是我认为它会如何完成... //Import os 模块这将允许您读取应用程序正在运行的操作系统类型 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)
}

推荐阅读