欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java运行shell脚本方法示例

程序员文章站 2024-02-18 11:46:52
现在通过commandhelper.execute方法可以执行命令,该类实现 复制代码 代码如下:package javaapplication3;import java...


现在通过commandhelper.execute方法可以执行命令,该类实现

复制代码 代码如下:

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 process = runtime.getruntime().exec(command);
        commandresult 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 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) {
}
}
        }
    }
}

commandhelper类使用了commandresult对象输出结果错误信息。该类实现

复制代码 代码如下:

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

现在看看调用代码的演示(main函数接受一个超时参数):

复制代码 代码如下:

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.getlocalizedmessage());
        }
    }

结果会创建一个testdir目录。
我尝试用这种方法创建通过ssh登录到远程机器,遇到两个问题:
1)如果希望没有人机对话方式,则需要使用命令sshpass -p password ssh user@targetip 'command'
2) 在netbeans上直接运行工程是不行的,因为权限不够,需要在终端里运行java javaapplication3.main
3) 很多命令不能运行,只有如pwd等命令可以运行,原因还不清楚,最好改用ganymed ssh-2库或者其他类似java库,我会在下一篇文章中介绍如何使用。