node.js - 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.
解决方案
下面将是我认为它会如何完成... //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)
}
推荐阅读
- asp.net-core - 未为 Azure AD B2C 自定义 totp 示例生成 QR 码
- javascript - 从多个按钮获取价值
- azure-logic-apps - 如何使用 Azure Logic App 将 PDF 转换为图像
- c# - ASP.Net Webforms 应用程序在访问支付网关后注销
- excel - J8空白时需要帮助保持单元格空白
- android - 重新启动后保留修改后的主机文件更改
- bash - 从两个文本文件中找到具有不同值的相同键
- javascript - 使用 NodeJS 下载大量图像
- cypress - 赛普拉斯视口无法准确反映指定的设备
- php - 如何使用 php 和 .htaccess 生成 SEO 友好的导航链接?