5

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.

Rafael Sofi-zada
  • 511
  • 3
  • 14
  • Do you have control over the servers? The simplest thing to do would be to install an OS-specific script on each server, so that your client has a *fixed* command to run, regardless of the remote server's OS. – chepner Jun 14 '21 at 16:52

1 Answers1

0

Below would be how i would think it would be done... //Import os module this will allow you to read the os type the app is running on 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)
}