【问题标题】:Query a remote server's operating system查询远程服务器的操作系统
【发布时间】:2019-10-05 04:13:20
【问题描述】:

我正在用 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...
});

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

【问题讨论】:

  • 您可以控制服务器吗?最简单的做法是在每台服务器上安装一个特定于操作系统的脚本,这样您的客户端就可以运行 fixed 命令,而不管远程服务器的操作系统如何。

标签: node.js shell ssh ssh2-sftp ssh2-exec


【解决方案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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-12
    • 2016-05-17
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    相关资源
    最近更新 更多