javascriptjavanode.jstypescriptssh2

Execute Linux commands using ssh2-promise in NodeJS on remote server


I am trying to execute command yum install <package_name> 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?


Solution

  • I made a mistake of calling an async function inside another async function , something like below,

    public async runCommand() {
         (async function () {
        try {
            const data = await ssh.exec("yum repolist all");
            console.log("resp: ", data);
        } catch (e) {
            console.log("Error - " + e);
        }
        })(); 
    }
    

    Changed the function like below and it worked .

    public async runCommand() { 
        try {
            const data = await ssh.exec("yum repolist all");
            console.log("resp: ", data);
        } catch (e) {
            console.log("Error - " + e);
        }
    }