From f47caf224b61a707b7f385d4ef6edc93055eb433 Mon Sep 17 00:00:00 2001 From: silenceqi Date: Sat, 21 Mar 2020 22:45:34 +0800 Subject: [PATCH] add ssh command test --- app/controller/command.js | 19 +++++++++++++++++++ app/service/command.js | 25 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 app/controller/command.js create mode 100644 app/service/command.js diff --git a/app/controller/command.js b/app/controller/command.js new file mode 100644 index 00000000..f7883789 --- /dev/null +++ b/app/controller/command.js @@ -0,0 +1,19 @@ +const Controller = require('egg').Controller; + +class CommandController extends Controller{ + async exec() { + const { ctx, service } = this; + const params = { + user: { type: 'string' }, + password: { type: 'string' }, + host:{ type:'string' }, + cmd: {type: 'string'}, + }; + console.log(ctx.request.body); + ctx.validate(params, ctx.request.body); + const res = await service.command.exec(ctx.request.body); + ctx.body = {data: res}; + } +} + +module.exports = CommandController; diff --git a/app/service/command.js b/app/service/command.js new file mode 100644 index 00000000..8eed1935 --- /dev/null +++ b/app/service/command.js @@ -0,0 +1,25 @@ +const Service = require('egg').Service; +var nssh = require('node-ssh'); + +class CommandService extends Service{ + async exec(params){ + let {host, user, password, port, cmd} = params; + port = port || 22; + var ssh = new nssh(); + return ssh.connect({ + host: host, + port: port, + username: user, + password: password + }).then(function(){ + return ssh.execCommand(cmd, {}).then(function(result) { + ssh.dispose(); + if(result.stderr != ""){ + return result.stderr; + } + return result.stdout; + }); + }); + } +} +module.exports = CommandService;