繁体   English   中英

如何从 node.js 应用程序通过 SSH 连接到服务器?

[英]How to SSH into a server from a node.js application?

var exec = require('child_process').exec;

exec('ssh my_ip',function(err,stdout,stderr){
    console.log(err,stdout,stderr);
});

这只是冻结 - 我猜,因为ssh my_ip要求输入密码,是交互式的,等等。如何正确地做到这一点?

有一个 node.js 模块被编写为使用 mscdex 称为 ssh2 的节点在 SSH 中执行任务。 可以在这里找到 您想要的示例(来自自述文件)是:

var Connection = require('ssh2');

var c = new Connection();
c.on('connect', function() {
  console.log('Connection :: connect');
});
c.on('ready', function() {
  console.log('Connection :: ready');
  c.exec('uptime', function(err, stream) {
    if (err) throw err;
    stream.on('data', function(data, extended) {
      console.log((extended === 'stderr' ? 'STDERR: ' : 'STDOUT: ')
                  + data);
    });
    stream.on('end', function() {
      console.log('Stream :: EOF');
    });
    stream.on('close', function() {
      console.log('Stream :: close');
    });
    stream.on('exit', function(code, signal) {
      console.log('Stream :: exit :: code: ' + code + ', signal: ' + signal);
      c.end();
    });
  });
});
c.on('error', function(err) {
  console.log('Connection :: error :: ' + err);
});
c.on('end', function() {
  console.log('Connection :: end');
});
c.on('close', function(had_error) {
  console.log('Connection :: close');
});
c.connect({
  host: '192.168.100.100',
  port: 22,
  username: 'frylock',
  privateKey: require('fs').readFileSync('/here/is/my/key')
});

此页面上的另一个库本身就很吓人。

所以我为它写了一个轻量级的包装器。 node-ssh也可以在GitHub 上获得 MIT 许可。

这是有关如何使用它的示例。

var driver, ssh;

driver = require('node-ssh');

ssh = new driver();

ssh.connect({
  host: 'localhost',
  username: 'steel',
  privateKey: '/home/steel/.ssh/id_rsa'
})
.then(function() {
  // Source, Target
  ssh.putFile('/home/steel/.ssh/id_rsa', '/home/steel/.ssh/id_rsa_bkp').then(function() {
    console.log("File Uploaded to the Remote Server");
  }, function(error) {
    console.log("Error here");
    console.log(error);
  });
  // Command
  ssh.exec('hh_client', ['--check'], { cwd: '/var/www/html' }).then(function(result) {
    console.log('STDOUT: ' + result.stdout);
    console.log('STDERR: ' + result.stderr);
  });
});

检查我的代码:

// redirect to https:
app.use((req, res, next) => {
    if(req.connection.encrypted === true) // or (req.protocol === 'https') for express
        return next();

    console.log('redirect to https => ' + req.url);
    res.redirect("https://" + req.headers.host + req.url);
});

最好的方法是使用promisifyasync/await 例子:

const { promisify } = require('util');
const exec = promisify(require('child_process').exec);

export default async function (req, res) {
  const { username, host, password } = req.query;
  const { command } = req.body;

  let output = {
    stdout: '',
    stderr: '',
  };

  try {
    output = await exec(`sshpass -p ${password} ssh -o StrictHostKeyChecking=no ${username}@${host} ${command}`);
  } catch (error) {
    output.stderr = error.stderr;
  }

  return res.status(200).send({ data: output, message: 'Output from the command' });
}

ssh 到主机的纯 js/node 方式。 特别感谢 ttfreeman。 假设 ssh 密钥在主机上。 不需要请求对象。


const { promisify } = require('util');
const exec = promisify(require('child_process').exec);
require('dotenv').config()

//SSH into host and run CMD 
const ssh = async (command, host) => {
let output ={};
  try {
    output['stdin'] = await exec(`ssh -o -v ${host} ${command}`)
  } catch (error) {
    output['stderr'] = error.stderr
  }

  return output
}


exports.ssh = ssh



暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM