java運行shell指令碼方法樣本

來源:互聯網
上載者:User

 利用Runtime.execute方法,我們可以在Java程式中運行Linux的Shell指令碼,或者執行其他程式

 現在通過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 controlSTART = 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 infoif (errorStreamReader.ready()) {StringBuilder buffer = new StringBuilder();String line;while ((line = errorStreamReader.readLine()) != null) {buffer.append(line);}result.setError(buffer.toString());}//parse infoif (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 yetisFinished = 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.Main3) 很多命令不能運行,只有如pwd等命令可以運行,原因還不清楚,最好改用Ganymed SSH-2庫或者其他類似Java庫,我會在下一篇文章中介紹如何使用。 
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.