tags:

views:

205

answers:

5

Hi I want to write a java script function which will execute the system shell commands (eg-> ls) and return the value.

How to create shell script file to achieve this.

Thanks Sunil Kumar Sahoo.

A: 

In java, depending on privileges:

 Runtime run = Runtime.getRuntime();
 Process pr = run.exec("ls");

 pr.waitFor();
    BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));

 String line = "";
 while ((line=buf.readLine())!=null) {
  System.out.println(line);
 }

In JavaScript you can't. They're really two quite separate things.

EDIT

My response was written when the question had the tags java and javascript. Since OP doesn't seem to make the distinction, I don't think I can say for sure which is being requested here.

David Hedlund
A: 

What if the client you are executing this javascript is running Windows? This is to say that what you are trying to achieve is not possible. Javascript is a client scripting language and runs in a sandboxed environment often inside a web browser which prevents it from accessing resources on the computer.

Darin Dimitrov
remember you do get server side javascript so isn't just a browser client language
AutomatedTester
@automatedtester True, but chances are whatever the OP is writing is targeted at the browser.
Justin Johnson
+2  A: 

This depends entirely on the JavaScript environment. Please elaborate.

For example, in Windows Scripting, you do things like:

var shell = WScript.CreateObject("WScript.Shell");
shell.Run("command here");
Matt
+1  A: 

This might be of interest: JavaScript and the SHELL Command

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");
Dana
A: 

Note: These answers are from a browser based client to a Unix based web server.

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

You can use an AJAX call to retrieve a dynamic page passing in your parameters via a 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 / ......

So in a nutshel, running from JS is just a bad, bad idea.... YMMV

Wayne
You essentially can't *in a cross-browser manner.* I believe only IE has hooks into the shell (via WSript/ActiveX).
Justin Johnson