Nodejs 如何使用node执行远程linux服务器命令

Nodejs 如何使用node执行远程linux服务器命令

RT。听说用Java能使用SSH+SCP实现在代码中直接执行远程linux命令,node 有没有类似的功能,或者工具?

5 回复

当然可以!在 Node.js 中,我们可以使用 ssh2node-ssh 这样的库来实现远程 Linux 服务器的命令执行。下面我将详细介绍如何使用这些库来实现这一功能。

使用 ssh2

ssh2 是一个非常强大的库,可以用来创建 SSH 客户端连接并执行远程命令。以下是一个简单的示例:

  1. 首先安装 ssh2 库:

    npm install ssh2
    
  2. 然后编写代码来连接到远程服务器并执行命令:

    const Client = require('ssh2').Client;
    
    const conn = new Client();
    conn.on('ready', () => {
        console.log('Connection :: Ready');
        // 执行远程命令
        conn.exec('ls -la', (err, stream) => {
            if (err) throw err;
            stream.on('close', (code, signal) => {
                console.log(`Stream :: Close :: Code: ${code}, Signal: ${signal}`);
                conn.end();
            }).on('data', (data) => {
                console.log(`STDOUT: ${data}`);
            }).stderr.on('data', (data) => {
                console.error(`STDERR: ${data}`);
            });
        });
    }).connect({
        host: 'your.remote.server.com',
        port: 22,
        username: 'yourusername',
        password: 'yourpassword'
    });
    

使用 node-ssh

node-ssh 是一个更现代且易于使用的库,提供了一种更简洁的方式来处理 SSH 连接。以下是使用 node-ssh 的示例:

  1. 首先安装 node-ssh 库:

    npm install node-ssh
    
  2. 然后编写代码来连接到远程服务器并执行命令:

    const { NodeSSH } = require('node-ssh');
    
    const ssh = new NodeSSH();
    
    ssh.connect({
        host: 'your.remote.server.com',
        port: 22,
        username: 'yourusername',
        password: 'yourpassword'
    }).then(() => {
        return ssh.execCommand('ls -la')
          .then((result) => {
              console.log(result.stdout);
              ssh.dispose(); // 关闭连接
          })
          .catch((error) => {
              console.error(error);
              ssh.dispose(); // 关闭连接
          });
    });
    

总结

以上两种方法都可以实现通过 Node.js 在远程 Linux 服务器上执行命令。ssh2 提供了更多的自定义选项,而 node-ssh 则更加简洁易用。根据你的需求选择合适的库即可。希望这些示例代码对你有所帮助!


直接调用 Sholl 命令行不?

{exec} = require "child_process"
exec "ssh user@0.0.0.0 'ls'"

firstly, google:ssh login without password. get the result and try

我是添加了公钥的, 倒忘了这点… 如果加公钥可以的话

要在 Node.js 中实现从本地机器执行远程 Linux 服务器上的命令,可以使用 ssh2node-ssh 这样的库来通过 SSH 连接到远程服务器并执行命令。

示例代码

这里以 node-ssh 库为例:

  1. 首先安装 node-ssh
npm install node-ssh
  1. 然后编写脚本执行远程命令:
const NodeSSH = require('node-ssh');

const ssh = new NodeSSH();

ssh.connect({
    host: 'your_remote_server_ip',
    username: 'your_username',
    password: 'your_password' // 或者你可以使用 privateKey 文件
})
.then(() => {
    return ssh.execCommand('ls -la')
    .then((result) => {
        console.log(result.stdout);
        console.log(result.stderr);
    });
})
.catch((err) => {
    console.error('连接失败或命令执行错误', err);
})
.finally(() => {
    ssh.dispose(); // 断开连接
});

解释

  1. 安装依赖:首先需要安装 node-ssh,这是一个用于建立 SSH 连接的库。
  2. 创建实例:通过 new NodeSSH() 创建一个 NodeSSH 实例。
  3. 连接服务器:使用 ssh.connect() 方法连接到远程服务器。你需要提供服务器 IP、用户名以及密码(或私钥路径)。
  4. 执行命令:通过 ssh.execCommand() 执行远程命令。这里我们执行了 ls -la 命令,并获取其输出。
  5. 处理结果:命令执行后,可以通过 .then() 处理标准输出和标准错误。
  6. 断开连接:最后使用 ssh.dispose() 断开与远程服务器的连接。

这种方式使得在 Node.js 中执行远程命令变得非常简单,只需几个步骤即可完成。

回到顶部