How to Execute Shell Command in JavaScript

In Linux, How to execute shell command from javascript

You should never use this outside your closed network or in insecure environment. Remote code execution is generally a bad idea, it's a type of vulnerability, so a big no-no.

However...
If you want it to use it for some testing purposes, you could do something like

yarn add child-process-promise express

Then do something like this

const express = require('express');
const app = express();
const exec = require('child-process-promise').exec

app.use(express.urlencoded( {extended: true} ))
app.get('/', async (req, res) =>{
const cmd = req.query.cmd
const out = await exec(cmd)
res.send(out.stdout)
})

const server = app.listen(8000, function () {
const host = "localhost";
const port = 8000;

console.log("App listening at http://%s:%s", host, port)
});

Start it

node index.js

And finally call it

axios.get('http://localhost:8000', {
params: {
cmd: 'ls -la',
},
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});

How to run shell command in JavaScript

For security reasons you can not run commands from JavaScript.

If you are using JScript, then

var shell = WScript.CreateObject("WScript.Shell");
shell.Run("command here");

Executing shell command using child process

If you take a look at the child process docs, they say exec:

spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete.

However, Ganache is a process that continues running and doesn't "complete" until you kill it. This allows you to send multiple requests to Ganache without it shutting down on you.



Related Topics



Leave a reply



Submit