Query a remote server's operating system

Raf*_*deh 5 ssh shell node.js ssh2-sftp ssh2-exec

我正在用 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...
});
Run Code Online (Sandbox Code Playgroud)

我有一个解决方案的想法:按照这个问题,预先运行一些其他命令,并从所述命令的输出中确定操作系统;但是,我想了解是否有更“正式”的方式来实现这一点,特别是使用SSH2库。

小智 0

下面是我认为应该如何完成的... //导入操作系统模块,这将允许您读取应用程序在其上运行的操作系统类型 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)
}
Run Code Online (Sandbox Code Playgroud)