在远程服务器上的NodeJS中使用ssh2-promise执行Linux命令

时间:2020-05-27 10:21:15

标签: javascript java node.js typescript ssh2

我正在尝试使用ssh2-promise软件包在远程linux服务器上执行命令yum install <package_name>, 但是我无法获取命令响应以进行进一步的处理和验证。

我尝试了以下方法,

// 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) 

我也尝试使用适当的try catch块,但仍抛出unhandledPromise异常。有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

我想您会在输出中得到以下内容:

<Buffer 5b 73 75 64 6f 5d 20 70 61 73 73 77 6f 72 64 20 66 6f 72 20 64 61 72 74 68 63 75 63 75 6d 62 65 72 3a 20>

您要做的就是使用JS的toString()函数将其转换为字符串。

答案 1 :(得分:0)

我在另一个异步函数中调用一个异步函数时犯了一个错误,如下所示,

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

按如下所示更改了功能,并且可以使用。

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