Nodejs ui页面是否可以运行shell cmd到远程机器并运行脚本

Can Nodejs ui page run shell cmd to remote machine and run script

本文关键字:运行 程机器 机器 脚本 cmd ui 是否 shell Nodejs      更新时间:2023-09-26

希望从nodejs-ui网页表单运行shell命令。form有一个"ssh{machinename}/path/to/script.sh"命令的输入字段。该页面将是nodejs单页应用程序。nodejs的新手。

这能做到吗?我已经搜索过了,但刚刚找到了带有php或python示例的页面。还看了argv和shelljs,但没有人提到我要做什么。Machine-A有一个单页应用程序,它的公钥已经插入到Machine-B中,执行的shell脚本就在那里。在cli上运行该命令有效。我希望用户在spa页面上运行自己的命令*仅限Nix环境。

到目前为止,我有以下内容。。。

package.json:
{ 
  "name": "TP",
  "version": "0.0.1",
  "description": "Testing Project",
  "private": true,
  "dependencies": {
    "express": "3.x",
    "hbs": "*"
  }
}

形式:

<form action="" method="post" enctype="multipart/form-data" style="margin:0; width:720px;">
  <fieldset>
    <!-- ENTER COMMAND -->
    <label for="test">Enter Test:</label>
    <input style="display: inline; width: 500px;" type="text" id="test_input" name="value" placeholder="Enter test command with correct params" />
    <!-- RUN COMMAND -->
    <input type="button" onclick="runTest()" value="Run Test!" style="float: right;" />
    <!-- CLEAR COMMAND -->
    <input type="button" name="testform" value="Clear Test" onclick="this.form.reset();" style="float: right;" />
    <br />
  </fieldset>
</form>

您看过ssh2shell包吗?

我发现ssh2-npm更符合我的需求,并且可以用来完成任务。你会看到我喜欢的简单。现在,通过前端按钮处理整个过程,并通过管道将stdout发送到mongodb。

npm安装ssh2

背景:bash命令必须使用转义字符用户私钥路径、主机和用户名具有sudo权限的用户目标vm 中的用户公钥

代码:

var Client = require('ssh2').Client;
var conn = new Client();
conn.on('ready', function() {
  console.log('Client :: ready');
  conn.shell(function(err, stream) {
    if (err) throw err;
    stream.on('close', function() {
      console.log('Stream :: close');
      conn.end();
    }).on('data', function(data) {
      console.log('STDOUT: ' + data);
    }).stderr.on('data', function(data) {
      console.log('STDERR: ' + data);
    });
        stream.end('cd /home/cruzcontrol/bin/ 'n sh flash_demo_test.sh 'n exit 'n');
  });
}).connect({
  host: '10.5.74.123',
  username: 'cruzcontrol',
  privateKey: require('fs').readFileSync('/home/cruzcontrol/.ssh/id_rsa')
});

现在这可能是多余的,但我想我会添加它,以防其他人觉得它有用。

服务页面和接收表单post数据可以使用nodejsexpress来完成。有很多基本的网站示例,比如节点中的简单网站,你可以使用它来启动和运行。

示例:

上面的链接提供了服务器代码示例。app.post函数中给出的SSH2shell示例。此示例未经过测试。建议按照上面的教程进行设置。.

var express = require('express')
    , logger = require('morgan')
    , app = express()
    , bodyParser = require('body-parser')
    , fs = require('fs')
    , Mustache = requires('mustache')
    , formPage = fs.readFileSync('./templates/myForm.xhtml');

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use( bodyParser.urlencoded({     // to support URL-encoded bodies
    extended: true
})); 
app.use(logger('dev'))
app.use(express.static(__dirname + '/static'))
//main page route
app.get('/', function (req, res, next) {
    try {
        var html = Mustache.parse(formPage, { title: 'My Form' })
        res.send(html)
    } catch (e) {
        next(e)
    }
})
//POST route
app.post('/', function (req, res) {
    //SSH2shell implementation
    var host = {
        server:  {     
            host:         '10.5.74.123',
            port:         22,
            userName:     'cruzcontrol', 
            privateKey: fs.readFileSync('/home/cruzcontrol/.ssh/id_rsa') },
        //Here you form command is set as the only command
        commands:         [ req.body.value ]
    };
    var SSH2Shell = require ('ssh2shell')
        , SSH = new SSH2Shell(host)
        , callback = function( sessionText ){
              //code here to return the sessionText and command in the form page.
              var html = Mustache.parse(formPage, { title: 'My Form',
                  value: req.body.value, 
                  result: sessionText});
              res.send(html);
        }       
    SSH.connect(callback);
})
app.listen(process.env.PORT || 3000, function () {
  console.log('Listening on http://localhost:' + (process.env.PORT || 3000))
})

只要nodeexpress为您的页面提供服务,SSH2shell就可以从表单提交中接收您的命令(值),运行它并在返回的表单页面中显示结果和命令。该示例使用模板引擎Mustache,因此myForm.xhtml需要页面表单html和几个标记来输出命令和响应。

SSH2shell没有检查密码设置或任何其他连接参数的代码,所以如果你不需要它进行身份验证,那么你就不必使用它。

SSH2外壳包裹SSH2.shell.

使SSH2shell工作所需的最低限度是:

  • host.server选项
  • host.com要求运行一组命令
  • 使用host.onEndSSH2shell.on('end')事件处理程序或回调函数来处理关闭连接的完整会话文本

就是这样。

可以通过使用文本框来处理多个命令,可以使用分隔符来分割命令,也可以将每一行视为一个命令,然后将它们推送到命令数组中。可以使用命令数组变量设置host.commands属性。响应(sessionText)处理将基本相同,只是req.body.value将是文本框内容。

有关SSH2shell用于SSH shell命令处理的更多详细信息,请参阅SSH2shell自述文件