sanketbajoria / ssh2-promise

ssh with promise/async await and typescript support
https://www.npmjs.com/package/ssh2-promise
MIT License
148 stars 24 forks source link

linux command execution on remote server #48

Closed asheikm closed 4 years ago

asheikm commented 4 years ago

I am trying to execute command yum install on a remote linux server using ssh2-promise package, But I could not get the command response back for further processing and validation.

I have tried the following,

// Node:33528) UnhandledPromiseRejectionWarning: Unhandled promise rejection. (async function(){ try { const data = await this.ssh.exec("yum repolist all"); console.log("resp: ", data); } catch(e) { console.log(e) } })(); // This fails

    const socket = await this.ssh.spawn("yum repolist all");
    socket.on('data', function(data) {
          console.log("resp: " , data); // I get binary data not the human readable output
    });

    // Node:33528) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
    this.ssh.exec("yum install <name>").then((data) => {
        console.log("resp: yum repolist all output: ", data); // This also fails and throws exception

    });

    // Throws again (Node:33528) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
    const output = await this.ssh.exec("yum upgrade <name>");
    console.log("resp: ", output) 

I tried with proper try catch block as well, still throws unhandledPromise Exception. Can someone help me figure this out?

sanketbajoria commented 4 years ago

@asheikm This should have worked. This is sample code you could try

var SSH2Promise = require('ssh2-promise');

var sshconfig = {
    host: 'localhost',
    username: 'sanket',
    password: 'sanket',
    port: 8331
}

var ssh = new SSH2Promise(sshconfig);

(async function () {
    try {
        const data = await ssh.exec("apk --help");
        console.log("resp: ", data);
    } catch (e) {
        console.log("Error - " + e);
    }
})(); 
asheikm commented 4 years ago

@sanketbajoria Thanks for the reply , I am on CentOS and i have to install a package through ssh. I tried the above code with command "yum install salt-minion" ,still the issue persists. Code is not in js but TS.

asheikm commented 4 years ago

@sanketbajoria , it worked, made a mistake of written an an (async function () {}); inside an another another async function, removed the additional asycnc call solved this issue