Java Run Shell Script method sample

Source: Internet
Author: User
Tags parse error readline ssh

  Using the Runtime.execute method, we can run Linux shell scripts in Java programs, or execute other programs

  Now through the Commandhelper.execute method can execute the command, the class implementation   code as follows: Package javaapplication3; Import Java.io.BufferedReader; Import java.io.IOException; Import Java.io.InputStreamReader; /**  *  * @author chenshu  */public class Commandhelper {   //default time out, in Millseconds     public static int default_timeout;     public static final int default_interval = 1000;     public static long START;     public static commandresult exec (String command) throws IOException, interruptedexception {    &N Bsp   Process process = Runtime.getruntime (). exec (command);         Commandresult Commandresult = wait (process);         if (process!= null) {Process.destroy ();        }       & nbsp return commandresult;    }     private static Boolean isovertime () {        return System.currenttimem Illis ()-START >= default_timeout;    }     private static Commandresult wait (process process) throws Interruptedexception, IOException {        BufferedReader errorstreamreader = null;         BufferedReader Inputstr Eamreader = null;         try {errorstreamreader = new BufferedReader (New InputStreamReader (Process.geterrorstream ()) ); InputStreamReader = new BufferedReader (New InputStreamReader (Process.getinputstream ())); Timeout control START = System.currenttimemillis (); Boolean isfinished = false; for (;;) {if (Isovertime ()) {Commandresult result = new Commandresult (); Result.setexitvalue (Commandresult.exit_value_timeout) ; Result.setoutput ("Command process timeout"); return result; } if (isfinished) {commandresult result = new Commandresult (); Result.setexitvalue (Process.waitfor ());//parse Error Info if (Errorstreamreader.ready ()) {StringBuilder buffer = new StringBuilder (); String Line; while (line =Errorstreamreader.readline ())!= null) {buffer.append (line);} result.seterror (Buffer.tostring ()); }//parse Info if (Inputstreamreader.ready ()) {StringBuilder buffer = new StringBuilder (); String Line; while (line = Inputstreamreader.readline ())!= null) {buffer.append (line);} result.setoutput (Buffer.tostring ()); return result; try {isfinished = true; Process.exitvalue ();} catch (Illegalthreadstateexception e) {//process hasn ' t finished yet I Sfinished = false; Thread.Sleep (Default_interval); }        } finally {if (Errorstreamreader!= null) {try {errorstreamreader.close ();} catch (IOE Xception e) {}} if (InputStreamReader!= null) {try {inputstreamreader.close ().} catch (IOException e) {}}   & nbsp    }    }}     Commandhelper class uses the Commandresult object output error message. The implementation of the class       code is as follows: Package javaapplication3; /**  *  * @author chenshu  */public class Commandresult {    PubliC static final int exit_value_timeout=-1;     private String output;     void Setoutput (String error) {        output=error;    }     Strin G GetOutput () {        return output;    }     int exitvalue;     void Setexitvalue (int value) {        exitvalue=value;    }     in T Getexitvalue () {        return exitvalue;    }     private String error;    /**      * @return the error      */    public String GetError () {         return error;    }    /**      * @param error The error to set      */    public void SetError (String error) {        this.error = error;    }}     &nbs P Now look at the demo of the calling code (the main function takes a time-out): The   code is as follows: Public static void Main (string[] args) {        try {int timeout = Integer.parseint (args[0]); Commandhelper.default_timeout = TIMEOUT; Commandresult result = Commandhelper.exec ("mkdir testdir"); if (result!= null) {System.out.println ("Output:" + result.getoutput ()); System.out.println ("Error:" + result.geterror ());}        } catch (IOException ex) {System.out.println ("IOException:" + ex.getlocalizedmessage ());        } catch (Interruptedexception ex) {System.out.println ("interruptedexception:" + Ex.getlocali Zedmessage ());        }    }     Results create a testdir directory. I tried this method to create an SSH login to the remote machine, encountered two problems: 1 if you want to have no man-machine conversation, you need to use the command sshpass-p password ssh user@targetip ' command ' 2) Working directly on NetBeans is not going to work because there is not enough permissions to run the Java Javaapplication3 in the terminal. Main 3) Many commands do not run, only such as PWD commands can run, the reason is not clear, it is best to switch to the Ganymed SSH-2 library or other similar Java library, I will explain in the next article how to use.  
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.