java中执行Windows或Unix命令

package com.nantian.itbms;

/**
 * 执行windows 命令或unix shell命令
 * @author panhong
 *
 */
public class WinUnixShell {

 public static void main(String[] args0) {
   String cmd="ping www.163.com";
  // String cmd="ipconfig";
  //String cmd = "ping 192.168.0.1";
  // String cmd="ipconfig";
  String result;
  try {
   result = exec(cmd);
   System.out.println("返回:\r\n" + result);
  } catch (Exception e) {
   System.out.println("执行出错:\r\n" + e.getMessage());
  }

 }

 /**
  * 执行window cmd或unix shell命令,如ipconfig
  *
  * @param youCmd
  * @return 执行命令状态

  * @throws Exception
  */
 public static String exec(String youCmd) throws Exception {
  String msg = null;
  if (youCmd == null || youCmd.length() < 1) {
   throw new Exception("请输入有效命令行命令");
  }

  try {
   hostInfo hostInfo = new hostInfo();
   String osName = hostInfo.getsysTYpe();
   String[] cmd = new String[3];
   if (("Windows 2000").equalsIgnoreCase(osName)
     || "Windows XP".equalsIgnoreCase(osName)) {
    cmd[0] = "cmd.exe";
    cmd[1] = "/C";
    cmd[2] = youCmd;
   } else if (osName.equals("Windows 95")) {
    cmd[0] = "command.com";
    cmd[1] = "/C";
    cmd[2] = youCmd;
   }
   if(osName.indexOf("unix")!=-1){ //unix操作系统
    cmd[0] = "ls";
    cmd[1] = "/C";
    cmd[2] = youCmd;
   }

    System.out.println("cmd:\r\n" + cmd[0] + " " + cmd[1] + " " +
    cmd[2]);
   Runtime rt = Runtime.getRuntime();
   Process proc = rt.exec(cmd);
   InputStreamPipe errorGobbler = new InputStreamPipe(proc
     .getErrorStream(), "ERROR");
   InputStreamPipe outputGobbler = new InputStreamPipe(proc
     .getInputStream(), "OUTPUT");
   errorGobbler.start();
   outputGobbler.start();

   int exitVal = proc.waitFor();// 等待事情干完,返回值0表示正确返回
   if (exitVal != 0) {
    msg = "失败";
    throw new Exception(errorGobbler.getOutputMsg()
      + "(异常退出值exitVal=" + exitVal + ")");
   } else {
    msg = outputGobbler.getOutputMsg();//返回命令执行结果
   }
  } catch (Exception e) {
   throw new Exception(e.getMessage());
  }

  return msg;
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值