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.

Similar Messages

  • 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]

  • 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.......

  • 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

  • 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.

  • Need help with Telnet command in JSP

    Here is the code I have been working on but it will not display the buffer to the page..
    String [] cmd1 = {"cmd.exe","/c","telnet hqsun1.xx.xxxxx.com"};
              Process n;
              String T = "" ;
              n = Runtime.getRuntime().exec(cmd1);
              BufferedReader in1 =
              new BufferedReader(new InputStreamReader(
              n.getInputStream()));
              while((T=in1.readLine()) != null)
              out.println(T+"");
    Maybe someone has done this before? I am trying to acomplish a telnet net session to the screen with some exicuted commands, because this tool is going to be used to help determine system status when the help desk needs to check on something.
    Thanks

    I don't want to be discouraging, but I'm not quite sure you've thought the problem through. You say that you'd like to create a web page capable of providing various pieces of information to the help desk, and you suggest ping and the output of various canned telnet commands as examples.
    What is preventing the help desk from just executing those commands at the command prompt?
    I realize that the people working the help desk are (ahem) there for a reason, but it is really much faster for me to just simply type "ping www.mpalfrey.com" at the prompt, then it is for me to fire up the web browser and wait for a response that way. You will likewise find that it is a lot more convenient to perform diagnosis on remote machines directly from the command prompt.
    Uh, it's kind of like giving someone a screwdriver, then saying, "oh wait a second" and making them wear an oven mitt in order to use the screwdriver.
    But, if you really want to do it this way, the best thing to do is create a wrapper class that directly calls the system command and captures the output to a stringbuffer. Then your JSP page simply has to clone that wrapper via a new() command and trigger it if you go the singleton route. The code would look something like this...
    <%@ import page="com.mpalfrey.shellcommands.ping" %>
    <%
       myPing foo = new myPing( request.getParameter( "victim" ) );
       foo.trigger();
    %>
    Ping results:
    <%=foo.results()%>JSP can do a lot of wonderful things, but that doesn't mean you have to do it that way. :)

  • 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);  }

  • Runtime.exec() - Need to execute unix command through pipe

    I want to execute something like this from Runtime.exec() :
    tar -czp -C /tmp/ myfile | ssh -qx -c blowfish remoteHost tar -xz -C /tmp/
    If I give the complete string as it is, then the system takes ssh command and the arguments to ssh (-qx) as arguments for tar and, thus, fails. I guess the reason is that the Runtime just takes the first string as the command and passes everything else as arguments to the command.
    How can I achieve this?

    The pipe symbol is interpreted by the shell, so you'd need the command you execute to be a shell (/bin/sh, /bin/csh /bin/bash, etc.) and the rest of it to be the args to that shell.
    Look at the man page for your shell. There should be a -c or somesuch argument that means "take the rest of this line as a command to execute in the shell I'm creating, which will then execute."
    Something like /bin/bash -c foo \| bar Not sure if you have to escape the pipe or not. Futz around with it and see.

  • 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.

  • 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.

  • 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?

  • Execute DOS command from SAP

    hi experts ,
    i need to execute DOS command from SAP .
    earlier we have 'GUI_EXEC' WS_EXECUTE , 'WS_DOWNLOAD' etc which are Obsolete now.
    as we are using ECC6.0. kindly guide how to do this.
    best regards,
    Rahul

    Try out...
    DSVAS_DOC_WS_EXECUTE_50
    or
    CL_GUI_FRONTEND_SERVICES=>EXECUTE
    <b><REMOVED BY MODERATOR></b>
    Thanks & Regards
    ilesh 24x7
    Message was edited by:
            Alvaro Tejada Galindo

Maybe you are looking for