2017-08-18 119 views
0
執行命令

我正在尋找一種方式來SSH方式連接到虛擬機,然後使用執行虛擬機內部的某些腳本Node.js的SSH到遠程計算機和Node.js的

到目前爲止,我已經創建自動登錄虛擬機的shell腳本,但我無法弄清楚如何前進。

用於登錄我的shell腳本到遠程服務器

spawn ssh [email protected] 
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; 

任何幫助表示讚賞感謝

+1

'node server.js' – Erazihel

+0

是的,我跑了,但我得到的輸出是這樣的:'錯誤:' – user7888003

回答

0

爲什麼不你用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來循環執行命令列表。