Javascript 如何在Javascript中执行shell命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1880198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to execute shell command in Javascript
提问by Sunil Kumar Sahoo
I want to write a JavaScript function which will execute the system shell commands (lsfor example) and return the value.
我想编写一个 JavaScript 函数,它将执行系统 shell 命令(ls例如)并返回值。
How do I achieve this?
我如何实现这一目标?
回答by Josh
Many of the other answers here seem to address this issue from the perspective of a JavaScript function running in the browser. I'll shoot and answer assuming that when the asker said "Shell Script" he meant a Node.js backend JavaScript. Possibly using commander.jsto use frame your code :)
这里的许多其他答案似乎从浏览器中运行的 JavaScript 函数的角度解决了这个问题。我会假设当提问者说“Shell Script”时他指的是 Node.js 后端 JavaScript,我会进行拍摄和回答。可能使用commander.js来使用你的代码框架:)
You could use the child_processmodule from node's API. I pasted the example code below.
您可以使用节点 API 中的child_process模块。我粘贴了下面的示例代码。
var exec = require('child_process').exec, child;
child = exec('cat *.js bad_file | wc -l',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
child();
Hope this helps!
希望这可以帮助!
回答by Mirek Rusin
...few year later...
……几年后……
ES6 has been accepted as a standardand ES7 is around the corner so it deserves updated answer. We'll use ES6+async/await with nodejs+babel as an example, prerequisites are:
ES6 已被接受为标准,而 ES7 即将到来,因此值得更新答案。我们将以 ES6+async/await 和 nodejs+babel 为例,先决条件是:
Your example foo.jsfile may look like:
您的示例foo.js文件可能如下所示:
import { exec } from 'child_process';
/**
* Execute simple shell command (async wrapper).
* @param {String} cmd
* @return {Object} { stdout: String, stderr: String }
*/
async function sh(cmd) {
return new Promise(function (resolve, reject) {
exec(cmd, (err, stdout, stderr) => {
if (err) {
reject(err);
} else {
resolve({ stdout, stderr });
}
});
});
}
async function main() {
let { stdout } = await sh('ls');
for (let line of stdout.split('\n')) {
console.log(`ls: ${line}`);
}
}
main();
Make sure you have babel:
确保你有 babel:
npm i babel-cli -g
Install latest preset:
安装最新预设:
npm i babel-preset-latest
Run it via:
通过以下方式运行它:
babel-node --presets latest foo.js
回答by Dan Dascalescu
I don't know why the previous answers gave all sorts of complicated solutions. If you just want to execute a quick command like ls, you don't need async/await or callbacks or anything. Here's all you need - execSync:
不知道为什么之前的答案给出了各种复杂的解决方案。如果您只想执行像 那样的快速命令ls,则不需要 async/await 或回调或任何东西。这就是你所需要的 - execSync:
const execSync = require('child_process').execSync;
// import { execSync } from 'child_process'; // replace ^ if using ES modules
const output = execSync('ls', { encoding: 'utf-8' }); // the default is 'buffer'
console.log('Output was:\n', output);
For error handling, add a try/catchblock around the statement.
对于错误处理,在语句周围添加一个try/catch块。
If you're running a command that takes a long time to complete, then yes, look at the asynchronous execfunction.
如果您运行的命令需要很长时间才能完成,那么是的,请查看异步exec函数。
回答by Matt
This depends entirely on the JavaScript environment. Please elaborate.
这完全取决于 JavaScript 环境。请详细说明。
For example, in Windows Scripting, you do things like:
例如,在 Windows Scripting 中,您可以执行以下操作:
var shell = WScript.CreateObject("WScript.Shell");
shell.Run("command here");
回答by Dana
In a nutshell:
简而言之:
// Instantiate the Shell object and invoke its execute method.
var oShell = new ActiveXObject("Shell.Application");
var commandtoRun = "C:\Winnt\Notepad.exe";
if (inputparms != "") {
var commandParms = document.Form1.filename.value;
}
// Invoke the execute method.
oShell.ShellExecute(commandtoRun, commandParms, "", "open", "1");
回答by keupsonite
With NodeJS is simple like that! And if you want to run this script at each boot of your server, you can have a look on the forever-serviceapplication!
使用 NodeJS 就是这么简单!如果您想在每次服务器启动时运行此脚本,您可以查看永久服务应用程序!
var exec = require('child_process').exec;
exec('php main.php', function (error, stdOut, stdErr) {
// do what you want!
});
回答by Wayne
Note: These answers are from a browser based client to a Unix based web server.
注意:这些答案是从基于浏览器的客户端到基于 Unix 的 Web 服务器。
Run command on client
在客户端运行命令
You essentially can't. Security says only run within a browser and its access to commands and filesystem is limited.
你基本上不能。安全说只能在浏览器中运行,并且它对命令和文件系统的访问是有限的。
Run ls on server
在服务器上运行 ls
You can use an AJAX call to retrieve a dynamic page passing in your parameters via a GET.
您可以使用 AJAX 调用来检索通过 GET 传入参数的动态页面。
Be aware that this also opens up a security risk as you would have to do something to ensure that mrs rouge hacker does not get your application to say run: /dev/null && rm -rf / ......
请注意,这也会带来安全风险,因为您必须采取措施确保 Mrs rouge 黑客不会让您的应用程序说运行:/dev/null && rm -rf / ......
So in a nutshel, running from JS is just a bad, bad idea.... YMMV
所以简而言之,从 JS 运行只是一个糟糕的主意...... YMMV
回答by August
Another post on this topic with a nice jQuery/Ajax/PHP solution:
关于这个主题的另一篇文章有一个很好的 jQuery/Ajax/PHP 解决方案:
回答by Anup Panwar
Here is simple command that executes ifconfigshell command of Linux
这是执行ifconfigLinux 的 shell 命令的简单命令
var process = require('child_process');
process.exec('ifconfig',function (err,stdout,stderr) {
if (err) {
console.log("\n"+stderr);
} else {
console.log(stdout);
}
});
回答by nonozor
In IE, you can do this :
在 IE 中,您可以这样做:
var shell = new ActiveXObject("WScript.Shell");
shell.run("cmd /c dir & pause");

