2

I want to trigger execution of a server-side script (.sh file) from JavaScript code running in a web browser.

I've searched google and no code that I've found is working for me.

5
  • You mean server side JavaScript? Commented Aug 14, 2012 at 2:52
  • Is this on the server or in the browser? And if it's in the browser, where is the sh file located: at the user's machine or on your server? Need more info. Commented Aug 14, 2012 at 2:59
  • i need to press button in browser and execute the sh file and the sh file is on my server Commented Aug 14, 2012 at 3:24
  • If this is client-side js, you need to use ajax or an html form to communicate with a server-side controller (which would be written in whatever language(s) you are using. e.g, PHP, Rails, Python, etc.). Commented Aug 14, 2012 at 3:38
  • my whole file is php. i using button onclick to call function. and i plan to execute the sh file in the function. however it didnt work Commented Aug 14, 2012 at 3:51

4 Answers 4

2

You need to first make a file in a server-side language (like PHP, Python, RoR, PERL, ASP.NET, or JSP) that runs the .sh file. Then you have to use Ajax to request that page.

In PHP, something like:

<?= shell_exec('sh /home/user/public_html/scripts/script.sh'); ?>

Then, for JS, something like:

<script src="//code.jquery.com/jquery-1.8.0.min.js"></script>
<script>
var runShellScript = function () {
    $.get('/scripts/script.php', function () {
        alert('Shell script done!');
    });
};

// Some stuff
runShellScript();
</script>

If you don't want to use jQuery or Ajax, you could probably get away with JSONP.

Sign up to request clarification or add additional context in comments.

3 Comments

i cannot execute for the script.php. and i am using apache
Apache should let you run PHP files.
What is the default path for "/scripts/script.php" ?
1

I believe You can't do this directly with client side JavaScript. However, you can invoke an url request to let server side language (PHP, Java, Ruby... almost any language) to do the task. And be sure to consider security issues.

Comments

1

Make sure you .sh file begins with:

#!/bin/sh
echo "Content-type: text/html"
echo ""

and the .htaccess file is set up to execute .sh files:

Options +ExecCGI
AddHandler cgi-script sh

Then you can simply call the file from the url using XMLHttpRequest. http://en.wikipedia.org/wiki/XMLHttpRequest, and maybe even have your script return some json object.

Comments

0

I don't know if Javascript opens .sh files in particular, but you can use the filereader API to open files in general.

1 Comment

i need to use button press to execute it in html. so i got no idea for it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.