Run shell scripts in Java

Source: Internet
Author: User
Tags parse error

By using the runtime.exe cute method, we can run the Linux Shell script in a Java program or execute other programs. Referring to this article on the Internet: http://lee79.javaeye.com/blog/418549 (thanks), I rearranged the code.
The commandhelper.exe cute method can be used to execute commands. The implementation code of this class is 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 {
Process = runtime.getruntime(cmd.exe C (command );
Commandresult = wait (process );
If (process! = NULL ){
Process. Destroy ();
}
Return commandresult;
}

Private Static Boolean isovertime (){
Return System. currenttimemillis ()-Start> = default_timeout;
}

Private Static commandresult wait (Process) throws interruptedexception, ioexception {
Bufferedreader errorstreamreader = NULL;
Bufferedreader inputstreamreader = 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
Isfinished = false;
Thread. Sleep (default_interval );
}
}

} Finally {
If (errorstreamreader! = NULL ){
Try {
Errorstreamreader. Close ();
} Catch (ioexception e ){
}
}

If (inputstreamreader! = NULL ){
Try {
Inputstreamreader. Close ();
} Catch (ioexception e ){
}
}
}
}
}

The commandhelper class uses the commandresult object output result error message. The implementation code of this class 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;
}

String getoutput (){
Return output;
}

Int exitvalue;

Void setexitvalue (INT value ){
Exitvalue = value;
}

Int 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;
}
}

Now let's take a look at the demo of calling code (the main function accepts a timeout parameter ):
Public static void main (string [] ARGs ){
Try {
Int timeout = integer. parseint (ARGs [0]);
Commandhelper. default_timeout = timeout;
Commandresult result = commandhelper.exe C ("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. getlocalizedmessage ());
}
}

The testdir directory is created.

I tried to use this method to create a remote machine to log on to the remote machine through SSH and encountered two problems:
1) if you do not want human-machine interaction, use the command sshpass-P password SSH user @ targetip 'command'
2) directly running the project on netbeans is not feasible. because of insufficient permissions, you need to run Java javaapplication3.main on the terminal.
3) A lot of commands can not run, only such as PWD commands can run, the reason is not clear, it is better to switch to the ganymed SSH-2 library or other similar Java library, I will introduce how to use in the next article.

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.