Solved

how does jsp run linux command?

Posted on 2004-04-21
4
1,496 Views
Last Modified: 2008-02-07
hi,

would like to know how does jsp run the linux command? what is the way to get this thing working?

amit
0
Comment
Question by:amit_spl
  • 3
4 Comments
 
LVL 4

Expert Comment

by:venishjoe
ID: 10876679
Hai,

Execute the following command:
Process p = Runtime.getRuntime().exec( "yourcommandgoeshere" );

Hope this helps

Regards
Venish
0
 
LVL 4

Expert Comment

by:venishjoe
ID: 10876686
Hai,

    If you want to execute the Linux command from Windows you should use telnet.

Regards
Venish
0
 

Author Comment

by:amit_spl
ID: 10886171
we tried doing :
Process p = Runtime.getRuntime().exec( "ls -l >/root/abc.txt" );

but there is no output!!

amit

0
 
LVL 4

Accepted Solution

by:
venishjoe earned 250 total points
ID: 10886846
Hai,

What is your OS?

Try with the following code

import java.io.*;
import java.lang.Process;
import java.lang.Runtime;

/**
 * This Program is used to execute an external application. developed to execute a C util for linux.
 * The output stream from the executed program is returned to System.out (stdout)
 * This program uses two threads, one thread kicks off another thread which executes the proccess. if the thread has not terminated within 120 seconds the main thread destroys the proccess and stops the executing thread, the return code is 10000, This handles process lockups.
 * @author Andrew Flack
 * @version v1.1 18th Oct 2001
 *  Added functionality to run system/promgram commands in the background whilst the main promgram continues.
 * @see java.lang.Process
 * @see java.lang.Runtime
 */


public class CommandRunner extends Thread{  

      
      /**
       * this stores the command passed by the user
       * @see #executeProccessBackGround(String)
       * @see #executeProgram(String)
       */
      private String stCommand;  

      /**
       * Temp return value from thread
       */
      private static int iRetVal;

      /*
       * The executed program runs using this process identifier
       */
      protected static Process p;

      /**
       * Temp storage of the stdout of the executed proccess read from an InputStream.
       */
      private static StringBuffer sb = null;

      /**
       * Thread that spawns process and monitors its status. once the proccess finishes execution the output of the program is outputted to console from this method.  
       * this thread talks to main program using static variables.
       * @see #sb
       * @see #p
       * @see #iRetVal
       */
      
      public void run(){      //thread method
            
            int iRetVal = -1; //initialize variable with error code (fail)

            try{

                        
                  //Process p;
                  int iOut = 0;
                  sb = new StringBuffer();
                  Runtime t = Runtime.getRuntime();

                  p = t.exec(stCommand);  //execute the passed command
                  

                  if(p.waitFor() != 0){  //wait for proccess to terminate
                        //System.out.println("Execution failed");
                  }
                  
                  iRetVal = p.exitValue();
                  InputStream pOut = p.getInputStream();  //get the output from the called program

                  while((iOut = pOut.read()) != -1){
                        //iOut = pOut.read();
                        sb.append((char)iOut);      //append the output to a stringbuffer
                  }

                  System.out.println("p.exitValue()= " + p.exitValue() + ", iRetVal = " + iRetVal );
                  System.out.print(sb.toString());  //print the output of the terminated proccess                  

                  //System.out.println("Thread Stoped");

            }
            //catch any errors that may of occured and display error to console (not web app)
            catch(IOException ioe){
                  System.out.println("IOException occurred when executing " + stCommand + ": " + ioe.getMessage());
            }
            catch(InterruptedException ie){
                  System.out.println("InterruptedException occurred when executing " + stCommand + ": " + ie.getMessage());
            }

            //the return value was returned as a static variable to the main thread
            

      }


      public String getGetOuputFromNonBackGroundProc(){
            return sb.toString();
      }

      /**
       * spawns a new proccess directly from this thread and continues the execution of this thread. allowing the program being executed to be monitored with getProccessOutputStream
       * @param stCommandin String the command to be executed on the machine. i.e. "ping 193.123.117.1"
       * @return InputStream, streaming output of the executed programs stdout.
       * @see #getProccessOutputStream()
       * @see #getProccessErrorStream()
       * @see #getExitValue()
       * @see #destroyProcess()
       */
      public InputStream  executeProccessBackGround(String stCommandin){
            
            try{
                        
                  //int iOut = 0;
                  //StringBuffer sb = new StringBuffer();
                  Runtime t = Runtime.getRuntime();

                  p = t.exec(stCommandin);  //execute the passed command

                  return p.getInputStream();
            }
            catch(Exception e){
                  System.out.println("Error: " + e.getMessage() );
            }
            return null;
            
      }
      
      /**
       * returns the protected process object to allow direct manipulation of the object.
       */
      public Process getProcessObj(){
            return p;
      }

      /**
       * Returns the process OutputStream (stdout) as an InputStream object for reading.
       * @see #executeProccessBackGround(String)

       */
      public OutputStream getProccessOutputStream(){
            return p.getOutputStream();
      }

      /**
       * Returns the process ErrorStream (stderr) as an InputStream object for reading.
       * @see #executeProccessBackGround(String)
       */

      public InputStream getProccessErrorStream(){
            return p.getErrorStream();
      }

      /**
       * Gets the return value from an executed proccess running in the background.
       * @see #executeProccessBackGround(String)
       * @return process exit value or -1 on error.
       */

      public int getExitValue(){
            try{
                  int i = p.exitValue();
                  return i;
            }
            catch(IllegalThreadStateException itse){
                  return -1;
            }
            catch(Exception e){
                  return -1;
            }
      }

      /**
       * Kills the process currently being executed
       */
      protected void destroyProcess(){
            p.destroy();
      }

            
      /**
       * executes an external  proccess in a child thread created by this method.
       * This methods thread will wait for the child thread to die, then get the return value of the executed proccess,
       * if the proccess does not die within 2 mins, then the chile thread is killed, killing the proccess being executed
       * @return int value representing the return value from the executed proccess. 16 is returned if the method times-out when waiting for the
       * proccess to finish
       * @param stCommandin String the command to executed passed as a string e.g. "ls /tmp/"
       */
      public int executeProgram(String stCommandin){

      
            CommandRunner crThrd = new CommandRunner();
            crThrd.stCommand = stCommandin;            //pass the command to run to the thread
            crThrd.start();  //start a new thread to execute the external program
            try{
                  int iwaitfor = 240;      //2 mins
                  while(crThrd.isAlive() == true && iwaitfor > 0){      //wait till thread dead or "iwaitfor" in time.
                        iwaitfor--;
                        
                        sleep(500);  //sleep this thread for 500ms
                  }      
                  if (crThrd.isAlive()){      //if thread is still alive kill it, with the proccess
                        p.destroy();
                        crThrd.stop();
                        iRetVal = 16;  //set a return value not zero (10000 in table as 9984 is added to get the errorcode displayed)
            
                  }
                  else{
                        iRetVal = p.exitValue();
                  }

            }
            catch (InterruptedException ie){
                  System.out.println("InterruptedException Occured : " + ie.getMessage());
            }
            System.out.println("Return Value in java is:" + iRetVal );
            return iRetVal;
      }

      
      /**
       * Same as  executeProgram(String) but allows the caller of the method to pass a timeout in seconds.
       * @see #executeProgram(String)
       * @return int value representing the return value from the executed proccess. 16 is returned if the method times-out when waiting for the
       * proccess to finish
       * @param stCommandin String the command to executed passed as a string e.g. "ls /tmp/"
       */

      public int executeProgram(String stCommandin, int iTimeout){

            CommandRunner crThrd = new CommandRunner();
            crThrd.stCommand = stCommandin;            //pass the command to run to the thread
            crThrd.start();  //start a new tread to execute the external program
            try{
                  
                  int iwaitfor = iTimeout * 2;      //this converts time passed into seconds
                  while(crThrd.isAlive() == true && iwaitfor > 0){      //wait till thread dead or 20 mins
                        iwaitfor--;
                        
                        sleep(500);  //sleep this thread for 500ms
                  }      
                  if (crThrd.isAlive()){      //if thread is still alive kill it, with the proccess
                        p.destroy();
                        crThrd.stop();
                        iRetVal = 16;  //set a return value not zero
            
                  }
                  else{
                        iRetVal = p.exitValue();
                  }
            }
            catch (InterruptedException ie){
                  System.out.println("InterruptedException Occured : " + ie.getMessage());
            }
            
            System.out.println("Return Value in java is:" + iRetVal );
            return iRetVal;
      }

      /**
       * Static test harness used for development of this class.
       * @param args[] String Not used
       */
      
      public static void main(String args[]){

            CommandRunner cr = new CommandRunner();
            int i = cr.executeProgram("rsh -l root 193.123.117.224 /usr/xmsutils/xms_ping/xms_ping -N000000104100 -P0 -I193.123.117.38");


            System.out.println("The proccess executed returned the value:" + i);

            //i = cr.executeProgram("gnp");
            //System.out.println("The proccess executed returned the value:" + i);

            

      }


}

Regards
Venish
0

Featured Post

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Many people tend to confuse the function of a virus with the one of adware, this misunderstanding of the basic of what each software is and how it operates causes users and organizations to take the wrong security measures that would protect them ag…
As the title indicates, I have done this before. It chills me everytime I update the OS on my phone, (http://www.experts-exchange.com/articles/18084/Upgrading-to-Android-5-0-Lollipop.html) because one time I did this and I essentially had a bricked …
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
Hi friends,  in this video  I'll show you how new windows 10 user can learn the using of windows 10. Thank you.

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question