我需要在node.js中执行一个bash脚本。基本上,脚本将在系统上创建用户帐户。我遇到了
this example,这给了我一个想法如何去。但是,脚本本身需要参数,如用户名,密码和用户的真实姓名。我仍然不知道如何传递这些参数到脚本做这样的事情:
- var commands = data.toString().split('\n').join(' && ');
任何人都有一个想法如何传递这些参数,并通过ssh连接在node.js内执行bash脚本。
谢谢
参见文档
here.它非常具体如何传递命令行参数。注意,你可以使用exec或spawn。 spawn有一个特定的参数为命令行参数,而使用exec你只是传递参数作为命令字符串的一部分来执行。
直接从文档,与解释评论内联
- var util = require('util'),spawn = require('child_process').spawn,ls = spawn('ls',['-lh','/usr']); // the second arg is the command
- // options
- ls.stdout.on('data',function (data) { // register one or more handlers
- console.log('stdout: ' + data);
- });
- ls.stderr.on('data',function (data) {
- console.log('stderr: ' + data);
- });
- ls.on('exit',function (code) {
- console.log('child process exited with code ' + code);
- });
而与exec
- var util = require('util'),exec = require('child_process').exec,child;
- child = exec('cat *.js bad_file | wc -l',// command line argument directly in string
- function (error,stdout,stderr) { // one easy function to capture data/errors
- console.log('stdout: ' + stdout);
- console.log('stderr: ' + stderr);
- if (error !== null) {
- console.log('exec error: ' + error);
- }
- });