Execute Linux Command via JSP

How can I execute Linux commands through a JSP page on a Red Hat Linux 6.1 Machine using Tomcat 3.0
Please Mail your answer
[email protected]

Hi Nick,
Thankx a lot, for suggestion,
I wanted to make a page which gives me a text box to write a command and below it shows the result of that command,
Say , I m in directory "/home/dhiraj"
and I write in command text box : "pwd"
it should give me the currrent path in result , which I can show in form of HTML as Results ,
(may be in a String form..)
same way if I write in command box : "ls -l"
it should Return me (say a String) the directory listing of the current path in result,
I have already tried the Runtime & Process class ,
Runtime rt = Runtime.getRuntime();
Process p =null;
p = rt.exec("command here");
p.waitFor();
it has following problems:
1) This way I m not able to get the result ..
2) I tried to make a zip file via my program it did not threw any exception , but could not execute...
I was confused is it 'coz of permission ( rights problem) or some programmatical error as the same program runs via a Java Class file ..
desperately waiting for ur suggestions
Dhiraj Agrawal
MCA student and a Trainee in a local Software House
reply to: [email protected]

Similar Messages

  • Need to execute Linux Commands in JSP

    Hi I am Srinivas,
    I am new to this forum,
    {color:#ff0000}I want to execute Linux Commands(which is remotely connected through putty) in a JSP Page.{color}
    {color:#0000ff}My requirement is to display df -h output on a JSP page.{color}
    This is because we will monitor disk space at regular intervals.
    Can anyone help me in this regard.
    Thanks & Regards
    Srinivas V.
    Edited by: Srini-XIUS on Mar 24, 2008 2:06 AM

    I think you might need the java 'robot' class.
    However, a JSP page displayed on a browser is running in a secure enviornment that will probably not let you access the computer its running on. Instead, create a serlvet back on the server that runs the robot class. The servlet will send the data to the jsp page for display. The jsp page can send commands to the servlet which will execute it via its robot class.

  • How to execute Linux command from Java app.

    Hi all,
    Could anyone show me how to execute Linux command from Java app. For example, I have the need to execute the "ls" command from my Java app (which is running on the Linux machine), how should I write the codes?
    Thanks a lot,

    You can use "built-in" shell commands, you just need to invoke the shell and tell it to run the command. See the -c switch in the man page for your shell. But, "ls" isn't built-in anyays.
    If you use exec, you will want to set the directory with the dir argument to exec, or add it to the command or cmdarray. See the API for the variants of java.lang.Runtime.exec(). (If you're invoking it repeatedly, you can most likely modify a cmdarray more efficiently than having exec() decompose your command).
    You will also definitely want to save the returned Process and read the output from it (possibly stderr too and get an exit status). See API for java.lang.Process. Here's an example
    java.io.BufferedReader br =
    new java.io.BufferedReader(new java.io.InputStreamReader(
    Runtime.getRuntime().exec ("/sbin/ifconfig ppp0").
    getInputStream()));
    while ((s = br.readLine()) != null) {...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Execute linux command from java

    I wanna execute linux command from java, bu the output has error:
    Return code = 1
    top: failed tty get
    The code as:
    import java.io.*;
    public class Execute {
         public static void main(String[] args) {
              try {
                   final Process process = Runtime.getRuntime().exec("top");
                   new Thread() {
                        public void run() {
                             try {
                                  InputStream is = process.getInputStream();
                                  byte[] buffer = new byte[1024];
                                  for (int count = 0; (count = is.read(buffer)) >= 0;) {
                                       System.out.write(buffer, 0, count);
                             } catch (Exception e) {
                                  e.printStackTrace();
                   }.start();
                   new Thread() {
                        public void run() {
                             try {
                                  InputStream is = process.getErrorStream();
                                  byte[] buffer = new byte[1024];
                                  for (int count = 0; (count = is.read(buffer)) >= 0;) {
                                       System.err.write(buffer, 0, count);
                             } catch (Exception e) {
                                  e.printStackTrace();
                   }.start();
                   int returnCode = process.waitFor();
                   System.out.println("Return code = " + returnCode);
              } catch (Exception e) {
                   e.printStackTrace();
    }Help please.

    Your code is probably good to run a program, that does not use terminal capabilities.
    Program "top" is a little bit more complicated - you have to run it with a real terminal.
    Try to run "xterm -e top". You can find an example how to run an external program
    from java code in cnd/gdb module on http://cnd.netbeans.org
    For example, take a look at openExternalProgramIOWindow() method on this page:
    http://cnd.netbeans.org/source/browse/cnd/gdb/src/org/netbeans/modules/cnd/debugger/gdb/proxy/Attic/GdbProxyCL.java?rev=1.1.2.6.2.5&only_with_tag=release551_fixes&view=markup
    It runs a command with external terminal.
    Thanks,
    Nik

  • Unable to execute Linux command from Java

    Hi,
    I am currently working on a code wherein i need to execute Linux command from Java. Below are some of the query i have.
    1) Is there any efficient method of running OS commands from Java, rather than using Runtime and Process method.
    2) Below is details of my code which fails in execution
    **-- Java Version**
    java version "1.6.0"
    OpenJDK Runtime Environment (build 1.6.0-b09)
    OpenJDK Server VM (build 1.6.0-b09, mixed mode)
    -- Program Code ----
    Where <path> = Path i put myself
    package test;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.*;
    public class GetInode{
         * @param args
         public static void main(String[] args) {
              GetInode test = new GetInode();
              test.getInode();
         public void getInode(){                    
              String command = "/usr/bin/stat -Lt <path>;
              System.out.println(command);
              Process process;
              Runtime rt;     
              try{
              rt = Runtime.getRuntime();               
              process = rt.exec(command);
              InputStreamReader isr = new InputStreamReader(process.getErrorStream());
              BufferedReader bre = new BufferedReader(isr);
              BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream());
              System.out.println(bre.readLine());
    System.out.println(br.readLine().split(" ")[7]);
              process.destroy();          
              }catch (Exception ex){
                   System.out.println("Error :- " + ex.getMessage());
    ------Output -------------
    /usr/bin/stat -Lt "<path>"
    /usr/bin/stat: cannot stat `"<path>"': No such file or directory
    Error :- null
    Can any one help me what is wrong and why i am unable to run the Linux command from Java.

    For clarity purpose............i m submitting actual code here
    --- Code ---
    package test;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.*;
    public class GetInode{
    * @param args
    public static void main(String[] args) {
    GetInode test = new GetInode();
    test.getInode();
    public void getInode(){               
    String command = "/usr/bin/stat -Lt \"/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt\"";
    System.out.println(command);
    Process process;
    Runtime rt;
    try{
    rt = Runtime.getRuntime();
    process = rt.exec(command);
    InputStreamReader isr = new InputStreamReader(process.getErrorStream());
    BufferedReader bre = new BufferedReader(isr);
    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
    System.out.println(bre.readLine());
    System.out.println(br.readLine().split(" ")[7]);
    process.destroy();
    }catch (Exception ex){
    System.out.println("Error :- " + ex.getMessage());
    --- Output ---
    [ratz]s0898671: java GetInode
    /usr/bin/stat -Lt "/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"
    /usr/bin/stat: cannot stat `"/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"': No such file or directory
    Error :- null
    -- Linux Terminal --
    If i copy the first line from the output and execute on Linux terminal her is the output that i get
    [ratz]s0898671: /usr/bin/stat -Lt "/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"
    /afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt 12003 24 81a4 453166 10000 1c 360466554 2 0 1 1246638450 1246638450 1246638450 4096
    Can you just assist me where am i really making mistake.......i was wondering if the command that i pass from Java....can be executed on Linux terminal why is it faling to run from java.........and when i print the Error Stream for process output........it show cannot Stat.......

  • Problem while executing batch file via jsp

    Scenario 1+
    I have a batch file(.bat) in which i have the following code
    mkdir d:\test\test1;
    mkdir d:\test\test2;
    mkdir d:\test\test3;
    mkdir d:\test\test4;
    mkdir d:\test\test5;
    mkdir d:\test\test6;
    mkdir d:\test\test7;
    mkdir d:\test\test8;
    mkdir d:\test\test9;
    mkdir d:\test\test10;when i double click on this or execute via cmd all the 10 directories are created successfully.
    Scenario 2+
    But when i try to execute this through a jsp using the following code,Only first 5 directories are created.Please help me in resolving the issue ASAP.Thanks in advance
    <%@page import="javax.swing.*"%>
    <%@page import="javax.swing.JFileChooser"%>
    <%@page import="java.awt.event.*"%>
    <%@page import="java.awt.*"%>
    <%@ page import="java.io.*"%>
    <%@ page import="java.util.*"%>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
        <title>untitled2</title>
      </head>
      <body><%
            Runtime.getRuntime().exec("d:\\test.bat");
                    System.out.println("Inside Try Block");
                  %>
        hi</body>
    </html>I am using Jdeveloper.

    carrera wrote:
    Then can u suggest any other way how i can invoke a batch file from html/jsp.I think what some of the previous posters wanted to make clear is that jsps are not the place to go calling batch files. Jsp's are normally the view part and don't actually trigger these type of actions directly. Call a servlet to do non-view things...
    If all you want to do is execute an ant file, look for examples for running ant through java api. f.i. here

  • Problem in executing Linux command from Java Programme.

    hi everybody,
    can anybody help me to solve one problem i have.
    i want to capture the output of linux command "grep" in my java programme.but it is not working properly .(maybe this sub-process doesn't have permission to read files)
    here is my code and corresponding outputs.
    import java.io.*;
    public class BSearch
    public static void main(String kj[])
    try
    Runtime rt=Runtime.getRuntime();
    String command="grep \"hello\" -r /usr/MyDir ";               
    Process rtProc=rt.exec(command);          
    InputStream is=rtProc.getInputStream();
    BufferedReader br =new BufferedReader(new InputStreamReader(is));     
    String line =null;
    while((line=br.readLine()) != null)
    System.out.println(br.readLine());
    br.close();
    catch(Exception e)
    System.err.println("Error in command "+e);               
    it finds "hello" pattern only in BSearch.class file although if i fire this command on LINUX prompt it
    shows all the files in /usr/MyDir which contain "hello" pattern.
    java programme output :
    Binary file /usr/MyDir/BSearch.class matches.
    linux command output :
    /usr/MyDir/one.txt: hello sdfs
    Binary file /usr/MyDir/BSearch.class matches.
    /usr/MyDir/two.txt: kjsdf hello sdfsdf
    will anybody help me solve this problem.

    It may be a Problem of Catching the Echoes back from the Processes...I have a Program which Captures the Echoes..see if it works
    import java.beans.PropertyChangeEvent;import java.beans.PropertyChangeListener;import java.beans.PropertyChangeSupport;import java.lang.ref.WeakReference;/** * Implements a proxy property change listener using a weak reference to avoid memory locking that would occur if it * was a strong reference. To understand this, we hve to understand that the property change listeners themselves are * hilding onto panels and other objects with strong java references. If the panel goes away while we are viewing an * object, we have a circular emory hold situation where the panel cant be collected because it has ahold of the * property and the property cannot because it has ahold of the pane. If we use weak references instead, then the hard * link between the listener and the producer is softened to almost nothing. */public class WeakPropertyChangeListener implements PropertyChangeListener {  /**   * A poperty change support object is included here so that the listener can remove   * himself from the listeners if the reference internally goes to null.   */  private PropertyChangeSupport pcs = null;  /** Holds the weak reference to the real listener. */  private WeakReference weakRef = null;  /**   * Constructs a new Proxy object for the given support and listener.   * @param pcs The property change support that this object will be using.   * @param pcl The real listener.   */  public WeakPropertyChangeListener(PropertyChangeSupport pcs, PropertyChangeListener pcl) {    if (pcs == null) throw new NullPointerException("pcs");    if (pcl == null) throw new NullPointerException("pcl");    this.pcs = pcs;    weakRef = new WeakReference(pcl);  } /** @see <{PropertyChangeListener}> */ public void propertyChange(PropertyChangeEvent changeEvent) {    Object referrant = weakRef.get();    if (referrant == null) {      pcs.removePropertyChangeListener(this);    } else {      ((PropertyChangeListener)referrant).propertyChange(changeEvent);    } } /** Returns true for comparison to referrant or this. */ public boolean equals(Object obj) {    if (obj instanceof WeakPropertyChangeListener) return super.equals(obj);    else if (obj != null)return obj.equals(weakRef.get());    else return false;  }}// snipet public void addPropertyChangeListener(PropertyChangeListener listener) {    this.propertyChangeSupport.addPropertyChangeListener(      new WeakPropertyChangeListener(this.propertyChangeSupport, listener));  } public void removePropertyChangeListener(PropertyChangeListener listener) {    this.propertyChangeSupport.removePropertyChangeListener(listener);  }

  • Executing linux command from Java code

    Hi ,
    I have a web application running on JBoss on Linux platform.
    I need to execut certain shell command of linux through servlet or JSP, so that I can display the command results on UI.
    If you have done something similer sort of thing then please shed some light on it.
    TIA,
    Sachin

    Sorry for the wrong post...please ignore this..
    Thanks,

  • Ho to execute dbschema command in jsp

    hi
    i am using informix as database server.In that dbschema is a utility that gives schema of table
    This command i have to excecute in jsp but i dont how?

    hey. Im actually using servlets and i know this isnt the right forum but i was given this url to come look here as it is similar to something i need.
    I just need to execute a batch file that sync's down a load of files and directories from perforce. i dont need to print them or see them i just nned it down so im assuming i will need more than just
    Process p = Runtime.getRuntime().exec("C:\\sync.bat");
    at the top of my code to run the batch file. does anyone have any idea what else i will need.

  • Executing linux command

    Hi Guys,
    From Java,I want to change the current user to "su",providing the password as well under linux.Do some tasks and go back to the last user.
    For example,I tried something as follows which didnt work!
    String cmd[]={"su","password"};
    Runtime.getRuntime().exec(cmd);
    Finish some tasks with the super user like deleting some files
    Go back to the previous user.
    String cmd[]={"Exit"};
    Runtime.getRuntime().exec(cmd);
    These are the commands normally used on a Linux shell command.How to do it from a java program.I use Java5.
    Thanks
    P

    Kohinoor wrote:
    These are the commands normally used on a Linux shell command.How to do it from a java program.I use Java5.I haven't tried this recently but I'm pretty sure you won't be able to do this because the password will have to be supplied from the keyboard driver and not written to the stdin (they are not the same) of the 'su' program. I would have thought your best bet would be to use SSH via one of the Java SSH libraries. Google is your friend.

  • Executing javascript command in jsp method

    here's the situation....
              I have a jsp page with three buttons at the bottom. One button reads
              "Save and Continue", another reads "Save and Quit" and the third reads
              "Quit". OnClick the page executes a java method that does
              verification for form objects, etc. THe problem here is the only way
              I know to close a window is self.close(); in javascript.
              Does anyone know how I may be able to excecute the method on click and
              then have that method close the window? IS this possible?
              

    No, I was not getting an error, but the file that I was executing was suppose to create two files and the two files were not created.
    However, I have since discovered that I needed to have write permission on the directory that I was writing too. So, it is working now, but thanks for responding.

  • Execute linux command and  getting its output in java

    i want to run a simple command from java: telnet localhost 8649 > report.txt
    how can I do this.

    See java.lang.ProcessBuilder

  • How to use Linux Command on JSP?

    Hi,
    I am trying to get the hostname and username of the JSP server using the Process object. However it doesn't work. Any advice? Thanks.
    Here's the code:
    try
    Process p = Runtime.getRuntime().exec("whoami");
    BufferedReader stdInput = new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    l_username = stdInput.readLine();
    out.println(l_username);
    Process q = Runtime.getRuntime().exec("hostname");
    stdInput = new BufferedReader(new
    InputStreamReader(q.getInputStream()));
    l_hostname = stdInput.readLine();
    out.println(l_hostname);
    catch (IOException e) {
    out.println("exception happened ");
    e.printStackTrace();
    }

    Writing raw Java code in a JSP instead of in a Java class and having problems with it doesn't make it a JSP problem. This question rather belongs in the 'New to Java' forum or 'Java Programming' forum, depending on the actual problem you struggle with.
    By the way, why tight coupling your application with the underlying platform by using platform-specific commandline stuff instead of just using the methods the Java API provides, such as those from java.lang.System and java.net.InetAddress and so on?

  • Executing batch File from Jsp

    I want to execute a batch file which is located at d:\build from a jsp
    I also want to give parameters to batch file.
    Actually my batch file is demo.bat and i want to execute this command via jsp
    demo Compile dev

    in a word - don't. that's not what jsps are for.
    you sound confused about where jsps actually run. get client and server straight in your head and then think about it again.
    %

  • Executing sudo linux commands through a JSP page.

    Hi,
    I need to execute some superuser commands through a JSP page under Linux.
    I added users apache and tomcat to the /etc/sudoers file with no password prompting.
    My JSP page works fine with any usual linux command, but when I call a “sudo cmd” I have a message (when reading the ErrorStream instead of the InputStream) that “sudo can’t be executed because it needs a tty” even when I call the shell before the sudo command.
    Here is a piece of my code (very basic):
    String cmd="linux_cmd";
    Process proc = Runtime.getRuntime().exec(cmd);
    InputStream stdin = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdin);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    while ( (line = br.readLine()) != null)
    out.println(line);
    Is there any way I can make sudo calls from a JSP page ?
    I know that making root calls from a web application is a bad thing, but for now security is not my concern.
    Thank you for any tips.

    JavaFan2 wrote:
    In fact, I help supervising a student project who is supposed to write an admin application to offert graphical interfaces for some security and system tools under Linux (like fdisk, iptables etc) using J2EE, ... something like Webmin.
    As I said, I know that is has a huge security risk but this app has the only purpose of learning J2EE, no security issues are treated.If you want to say "I will leave my office door open because there's no security risk in doing that" then that's a valid statement. But what you are trying to do here isn't the equivalent of leaving your office door open. It's the equivalent of finding a master key for all the offices in the world. And as such it is in fact a serious security risk which should not be circumvented.
    And no, it's no good saying "But I'm only going to use this all-powerful master key to open my own office door". If you get the key then anybody else can get the key too.

Maybe you are looking for

  • I have deleted safari on os x 10.7.1  , and now I can not install it , he say " This update requires mac ox 10.6 "

    I have problems in the Safari browser  , and I have deleted the program using the "Clean My Mac" App and now I can not install it , he say " This update requires mac ox 10.6 " I would like to install the Safari browser on my system Lion os x 10.7.1 -

  • Imovie shimmer

    I recently purchased a 15" macbook pro with retina display. When I import a video clip from my Sony HDR-HC9 camcorder into imovie 11, the picture shimmers. I viewed the clip directly on a TV monitor and the quality was fine. Also I did not have this

  • Suitable external monitor for 5800?

    Love the SatNav on my 5800, but I'm getting old and the screen is too small.  This isn't helped by the fact that I'm slightly colour blind and the colour are sometimes less than helpful. Anyway, the question is does anyone use this phone with an exte

  • Contribute rewriting urls with "|" in them

    We have the following code in a template: <a href="*|UNSUB|*">Unsubscribe From This List</a> And upon publish, Contribute rewrites it to either: <a href=*/UNSUB/*">Unsubscribe From This List</a> ...switching "|" for "/" if it's not in an editable are

  • Tabs suddenly switch to a new window

    Somehow with these newer versions of FF (I'm using the latest), every now and then I'll be in a tab, when suddenly the tab becomes a new window or instance of FF. This is very annoying, since now the tab and site are no longer loaded into one instanc