The NoteBook of EricKong

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  610 Posts :: 1 Stories :: 190 Comments :: 0 Trackbacks

1.Windows 很简单,写出来时为了和linux对比

   public void execWindowsCmd(String cmd) throws Exception {
      Runtime rt = Runtime.getRuntime();
      Process ppp = rt.exec(cmd);
      //input
      InputStreamReader ir = new InputStreamReader(ppp.getInputStream());
      LineNumberReader input = new LineNumberReader(ir);

      String line;
      while ((line = input.readLine()) != null)
         com.pub.Log.logger.debug(this.getClass().getClass() + " " +
                                           line);

      //error
      ir = new InputStreamReader(ppp.getErrorStream());
      input = new LineNumberReader(ir);
      while ((line = input.readLine()) != null)
         com.pub.Log.logger.debug(this.getClass().getClass() + " " +
                                           line);

      ppp.waitFor();
   }

 

2. Linux :首先要确保对于命令,允许Web服务器的用户是否有权限,普通命令和windows没什么区别。Linux管道命令不能这样直接执行,下面是具体实现fang

   public void execLinuxCmd(String cmd) throws Exception {
      Runtime rt = Runtime.getRuntime();
      File f = new File(this.fileName + PDU_SHELL);
      BufferedWriter bw = new BufferedWriter(new FileWriter(f));
      bw.write("#!/bin/bash");
      bw.newLine();
      bw.write(cmd);  //把命令写入一个文本shell文件
      bw.flush();
      bw.close();
      cmd = f.getAbsolutePath();

      Process ppp = rt.exec("chmod a+x " + cmd);  //授权该shell文件可以执行
      ppp.waitFor();

      ppp = rt.exec(cmd);  //执行shell

      //input
      InputStreamReader ir = new InputStreamReader(ppp.getInputStream());
      LineNumberReader input = new LineNumberReader(ir);

      String line;
      while ((line = input.readLine()) != null)
         com.pub.Log.logger.debug(this.getClass().getClass() + " " +
                                           line);

      //error
      ir = new InputStreamReader(ppp.getErrorStream());
      input = new LineNumberReader(ir);
      while ((line = input.readLine()) != null)
         com.pub.Log.logger.debug(this.getClass().getClass() + " " +
                                           line);

      ppp.waitFor();

   }

posted on 2014-12-24 12:01 Eric_jiang 阅读(152) 评论(0)  编辑  收藏 所属分类: Java

只有注册用户登录后才能发表评论。


网站导航: