如何在Javascript中执行shell命令

Sun*_*hoo 108 javascript

我想编写一个JavaScript函数,它将执行系统shell命令(ls例如)并返回值.

我该如何实现这一目标?

Jos*_*osh 119

这里的许多其他答案似乎都是从浏览器中运行的JavaScript函数的角度来解决这个问题.我会拍摄并回答,假设当提问者说"Shell Script"时,他的意思是Node.js后端JavaScript.可能使用commander.js来使用框架你的代码:)

您可以使用节点API中的child_proccess模块.我粘贴了下面的示例代码.

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();
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 除了一件事.你会得到错误"孩子不是一个功能".对exec()的调用执行命令 - 不需要调用child().不幸的是,只要子进程有输出内容,就不会调用回调 - 只有当子进程退出时才会调用它.有时候这没关系,有时则没有. (10认同)
  • 为避免回调,您可以使用 [execSync](/sf/answers/3680258641/)。 (3认同)
  • 谁谈到了浏览器?它只说了 JavaScript,仅此而已。 (3认同)

Mir*_*sin 38

......几年后......

ES6已被接受为标准,ES7即将到来,因此值得更新答案.我们将使用ES6 + async/await和nodejs + babel作为示例,先决条件是:

您的示例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();
Run Code Online (Sandbox Code Playgroud)

确保你有巴贝尔:

npm i babel-cli -g
Run Code Online (Sandbox Code Playgroud)

安装最新预设:

npm i babel-preset-latest
Run Code Online (Sandbox Code Playgroud)

运行它:

babel-node --presets latest foo.js
Run Code Online (Sandbox Code Playgroud)

  • @Virus721:您想在哪个 JavaScript 运行时执行 shell 命令? (7认同)
  • 没有人要求 Node.js 解决方案。它只说 JavaScript。 (5认同)
  • 如果只需要执行快速命令,则所有异步/等待都是多余的。您可以只使用[execSync](/sf/answers/3680258641/)。 (3认同)

Dan*_*scu 26

我不知道为什么之前的答案给出了各种复杂的解决方案.如果你只想执行类似的快速命令ls,则不需要async/await或callbacks或任何东西.这就是你需要的全部 - 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);
Run Code Online (Sandbox Code Playgroud)

对于错误处理,请在语句周围添加try/ catch块.

如果您正在运行需要很长时间才能完成的命令,那么请查看异步exec函数.

  • execSync 是否适用于 Mac、Linux 和 Windows 命令? (3认同)

Mat*_*att 17

这完全取决于JavaScript环境.请详细说明.

例如,在Windows Scripting中,您执行以下操作:

var shell = WScript.CreateObject("WScript.Shell");
shell.Run("command here");
Run Code Online (Sandbox Code Playgroud)

  • 是否可以在类似Unix的操作系统(如Linux)中执行相同的操作? (16认同)
  • 这就是我一直在寻找的。那些谈论 Node.js 的人很烦人。谁在这里要求 Node.js ?没有人这么做。 (2认同)

Dan*_*ana 14

简而言之:

// 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");
Run Code Online (Sandbox Code Playgroud)

  • [ActiveXObject仅在IE浏览器上可用.](http://stackoverflow.com/questions/11101641/activexobject-is-not-defined-and-cant-find-variable-activexobject#answer-11101655) (7认同)
  • 对于运行哪个Web浏览器似乎有很多麻烦,但是人们应该意识到JavaScript也是一种完全有效的Windows shell脚本语言. (5认同)

小智 7

NodeJS很简单!如果您想在服务器的每次启动时运行此脚本,您可以查看永久服务应用程序!

var exec = require('child_process').exec;

exec('php main.php', function (error, stdOut, stdErr) {
    // do what you want!
});
Run Code Online (Sandbox Code Playgroud)


Ali*_*kan 7

function exec(cmd, handler = function(error, stdout, stderr){console.log(stdout);if(error !== null){console.log(stderr)}})
{
    const childfork = require('child_process');
    return childfork.exec(cmd, handler);
}
Run Code Online (Sandbox Code Playgroud)

这个函数可以很容易地使用,例如:

exec('echo test');
//output:
//test

exec('echo test', function(err, stdout){console.log(stdout+stdout+stdout)});
//output:
//testtesttest
Run Code Online (Sandbox Code Playgroud)


Way*_*yne 5

注意:这些答案是从基于浏览器的客户端到基于Unix的Web服务器。

在客户端上运行命令

您基本上不能。安全性说只能在浏览器中运行,并且它对命令和文件系统的访问受到限制。

在服务器上运行ls

您可以使用AJAX调用来检索通过GET传递参数的动态页面。

请注意,这还会带来安全风险,因为您必须做一些事情以确保rouge hacker先生不会让您的应用程序运行:/ dev / null && rm -rf / ......

因此,总的来说,从JS运行只是一个不好的主意。


Anu*_*war 5

这是执行ifconfigLinux shell命令的简单命令

var process = require('child_process');
process.exec('ifconfig',function (err,stdout,stderr) {
    if (err) {
        console.log("\n"+stderr);
    } else {
        console.log(stdout);
    }
});
Run Code Online (Sandbox Code Playgroud)