java 运行shell命令及脚本

仅供参考;
1.java运行shell命令基本类介绍,Process类与Runtime类

1.1 Process类:
Process类是一个抽象类,通常用ProcessBuilder.start() 和 Runtime.exec 方法创建一个本机进程。并返回 Process 子类的一个实例,该实例可用来控制进程并获得相关信息。Process 类提供了执行从进程输入、执行输出到进程、等待进程完成、检查进程的退出状态以及销毁(杀掉)进程的方法。

1.2 Runtime类:
            Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntimemethod.  
   每个java应用程序都有一个Runtime实例,用于和操作系统运行环境交互,可以用getRuntime()方法来获取一个Runtime实例。

1.3执行一条shell命令
String commend=".....";//一条shell命令
Process pro=Runtime.getRuntime().exec(commend);
//exec方法会返回一个单独的进程用来管理子进程(A new Process object for managing the subprocess)。
        pro.waitFor() ;

          //导致当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。(causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.)也可以意味着命令运行成功,没有发生堵塞。

当然exec有很多重载方法,具体看api。


1.4  注意事项

          1.4 . 1 当调用的外部命令中包含重定向(<、>),管道( | ) 命令时,exec(String command)的版本不能正确解析重定向、管道操作符。所以需要使用exec(String [] cmdArray)。

   eg: echo "hello world" > /home/admin/newFile.txt

                               ls -e | grep java

                           需要使用如下的调用方式

                           String []cmdArray = new String[]{ "/bin/sh", "-c", "ls -e | grep java"};

                           Runtime.getRuntime().exec(cmdArray);


1.4 .2. 永远要在调用waitFor()方法之前读取数据流

           永远要先从标准错误流中读取,然后再读取标准输出流


  1.4 .3. 另外一个需要注意的地方是:

     如果调用的脚本中存在像sudo这样的需要tty的命令时,使用

            String []cmdArray = new String[]{ "/bin/sh", "-c", "yourscriptname"};

  这样的调用方式,会为脚本执行创建出一个tty环境,否则,运行过程会提示"sorry, you must have a tty to run xxx"的错误


2.Java 实现SSH协议的项目有很多,如JFTP,trilead SSH,JSCHganymed SSH等。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章