我正在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
库。
答案 0 :(得分: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)
}