Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute server-side shell script on button click

I am trying to execute a shell script that resides in my server. And I need to get the (string) result of this shell script after execution. However, this script should only be triggered only when a certain button in my ReactJS app is pressed.

I spent considerable amount of time looking for answer. So far, all the answers point to an idea of creating a web service then have the app call the service on button click. But none of the answers pointed how exactly this is done nor any of the answers point to any article that discusses this approach. (Sorry if this is a basic approach, but I just learned ReactJS last month from Udemy.)

Would you mind creating a simple code that demonstrates communication between the 'shell script web service' and a button (onClick)? Or at least provide an article link that discusses this approach?

Thanks for any help.

EDIT: What I tried so far is How to execute shell command in Javascript. But comments say that this will not work on browser. I guess this is the code that I need to write in my web service?

like image 659
user1506104 Avatar asked Mar 09 '26 11:03

user1506104


1 Answers

Finally, I got it. Below is what I did.

Step1: create a page/api/execute.js (name your file appropriately)

Step2: put this sample shell script (ls command) in your execute.js

export default function handler(req, res) {
  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'
  const splitted = output.split(/\r?\n/);  
  const filtered = splitted.filter( e => {
    return e !== '';
  });

  res.status(200).json(JSON.stringify(filtered))
}

Step3: In your react component, add a button with onClick handler like so:

<Button primary onClick={this.execCommand}>Execute Shell Command</Button>

Step4: create your execCommand function:

async execCommand() {
    const req = await fetch("/api/execute");
    const data = await req.json();
    console.log(data);
}

Step5: Click your button and see the output on your browser's console.

Cheers!

like image 78
user1506104 Avatar answered Mar 11 '26 02:03

user1506104



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!