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;