add ssh command test

This commit is contained in:
silenceqi 2020-03-21 22:45:34 +08:00
parent d7fae18732
commit f47caf224b
2 changed files with 44 additions and 0 deletions

19
app/controller/command.js Normal file
View File

@ -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;

25
app/service/command.js Normal file
View File

@ -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;