我正在寻找一种通过 SSH 连接到虚拟机然后使用 Node.js 在虚拟机中执行某些脚本的方法
到目前为止,我已经创建了自动登录到虚拟机的 shell 脚本,但我无法弄清楚如何继续。
登录远程服务器的shell脚本
spawn ssh root@localhost
expect "password"
send "123456"
send "\r"
interact
这是我的 server.js
var http = require('http');
var execProcess = require("./exec_process.js");
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
execProcess.result("sh sshpass.sh", function(err, response){
if(!err){
res.end(response);
}else {
res.end("Error: ", err);
}
});
}).listen(3000);
console.log('Server listening on port 3000');
exec_process.js
var exec = require('child_process').exec;
var result = function(command, cb){
var child = exec(command, function(err, stdout, stderr){
if(err != null){
return cb(new Error(err), null);
}else if(typeof(stderr) != "string"){
return cb(new Error(stderr), null);
}else{
return cb(null, stdout);
}
});
}
exports.result = result;
感谢任何帮助
最佳答案
你为什么不使用simple-ssh ?
我做了一个简单的例子,说明如何加载一个包含命令列表的文件并在链中执行它们。
exampleList :(命令必须换行)
echo "Testing the first command"
ls
sshtool.js :(它可能有问题,例如:如果任何命令包含 \n
)
const _ = require("underscore");
//:SSH:
const SSH = require('simple-ssh');
const ssh = new SSH({
host: 'localhost',
user: 'username',
pass: 'sshpassword'
});
//example usage : sshtool.js /path/to/command.list
function InitTool(){
console.log("[i] SSH Command Tool");
if(process.argv[2]){AutomaticMode();}
else{console.log("[missing argument : path to file containing the list of commands]");}
}
//:MODE:Auto
function AutomaticMode(){
const CMDFileName = process.argv[2];
console.log(" ~ Automatic Command Input Mode");
//Load the list of commands to be executed in order
const fs = require('fs');
fs.readFile(process.argv[2], "utf8", (err, data) => {
if(err){console.log("[!] Error Loading Command List File :\n",err);}else{
var CMDList = data.split("\n"); // split the document into lines
CMDList.length = CMDList.length - 1; //fix the last empty line
_.each(CMDList, function(this_command, i){
ssh.exec(this_command, {
out: function(stdout) {
console.log("[+] executing command",i,"/",CMDList.length,"\n $["+this_command+"]","\n"+stdout);
}
});
});
console.log("[i]",CMDList.length,"commands will be performed.\n");
ssh.start();
}
});
}
//:Error Handling:
ssh.on('error', function(err) {
console.log('[!] Error :',err);
ssh.end();
});
InitTool();
它使用 underscore用于遍历命令列表。
关于javascript - SSH 进入远程机器并在 Node.js 中执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45764488/