zoukankan      html  css  js  c++  java
  • Java /Jsp 执行操作系统命令 windows/Linux

    原创  Java /Jsp 执行操作系统命令 windows/Linux 收藏

    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();

       }

    转载自:http://blog.csdn.net/winderain/archive/2006/04/22/673497.aspx

    感谢原作者

  • 相关阅读:
    Kafka 入门(四)-- Python Kafka Client 性能测试
    XShell连接阿里云服务器出现”用户密钥加载失败:请确定输入的密码“处理办法
    优化自动化测试流程,使用 flask 开发一个 toy jenkins工具
    我做了回视频,告诉你需要用到哪些工具
    提问的基本原则
    12 月31 日返利系统问题复盘
    外部prometheus监控k8s(k3s)集群
    一个Java类在运行时候,变量是怎么在JVM中分布的呢?
    JVM学习第二篇思考:一个Java代码是怎么运行起来的-下篇
    JVM学习第一篇思考:一个Java代码是怎么运行起来的-上篇
  • 原文地址:https://www.cnblogs.com/lechie/p/2383217.html
Copyright © 2011-2022 走看看