首页 新闻 会员 周边

在servlet中调用windows cmd 命令无法获取cmd的输出,直接在main方法调用运行正常

0
[已解决问题] 解决于 2016-08-29 08:33

写了一个工具类用于获取本地的MAC地址,工具类中直接写了一个main方法正常运行,但是在servlet中执行获取MAC的方法,无法获取到CMD的输出是怎么回事啊?

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 与系统相关的一些常用工具方法.
 * 
 * @author lvbogun
 * @version 1.0.0
 */
public class SystemTool {

    /**
     * 获取当前操作系统名称. return 操作系统名称 例如:windows xp,linux 等.
     */
    public static String getOSName() {
        return System.getProperty("os.name").toLowerCase();
    }

    /**
     * 获取本机ip地址,并自动区分Windows还是linux操作系统
     * 
     * @return String
     */
    public static String getLocalIP() {
        String sIP = "";
        InetAddress ip = null;
        String os = getOSName();
        try {
            // 如果是Windows操作系统
            if (os.toLowerCase().startsWith("windows")) {
                ip = InetAddress.getLocalHost();
            }
            // 如果是Linux操作系统
            else {
                boolean bFindIP = false;
                Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
                        .getNetworkInterfaces();
                while (netInterfaces.hasMoreElements()) {
                    if (bFindIP) {
                        break;
                    }
                    NetworkInterface ni = (NetworkInterface) netInterfaces
                            .nextElement();
                    // ----------特定情况,可以考虑用ni.getName判断
                    // 遍历所有ip
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        ip = (InetAddress) ips.nextElement();
                        if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() // 127.开头的都是lookback地址
                                && ip.getHostAddress().indexOf(":") == -1) {
                            bFindIP = true;
                            break;
                        }
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (null != ip) {
            sIP = ip.getHostAddress();
        }
        return sIP;
    }

    /**
     * 获取MAC地址
     * @return
     * @throws Exception
     */
    public static String getLocalMacAddress() {
        String mac = "";
        String os = getOSName();
        if (os.toLowerCase().startsWith("windows")) {
            try {
                String command = "cmd.exe /c ipconfig /all";
                Process p = Runtime.getRuntime().exec(command);
                /*try {
                    p.waitFor();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                p.getOutputStream().flush();*/
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        p.getInputStream(), "GBK"));
                String line;
//在servlet中执行时,while循环中的语句不会执行。
                while ((line = br.readLine()) != null) {
                    if (line.indexOf("Physical Address") > 0 
                            || line.indexOf("物理地址") > 0
                            ) {
                        int index = line.indexOf(":");
                        index += 2;
                        mac = line.substring(index);
                        break;
                    }
                }
                
                br.close();
                return mac.trim();
            } catch (IOException e) {
            }
        } else if (os.startsWith("Linux")) {
            String command = "/bin/sh -c ifconfig -a";
            Process p;
            try {
                p = Runtime.getRuntime().exec(command);
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        p.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    if (line.indexOf("HWaddr") > 0) {
                        int index = line.indexOf("HWaddr") + "HWaddr".length();
                        mac = line.substring(index);
                        break;
                    }
                }
                br.close();
            } catch (IOException e) {
            }
        }
        mac = mac.trim();
        return mac;
    }

    /**
     * 测试用的main方法.
     * 
     * @param argc
     *            运行参数.
     * @throws Exception
     */
    public static void main(String[] argc) throws Exception {
        System.out.println(getLocalIP());
        System.out.println(getLocalMacAddress());
    }
}
泱泱的主页 泱泱 | 初学一级 | 园豆:2
提问于:2016-04-07 20:01
< >
分享
最佳答案
0

如下是一直用的,没啥问题

public static final String RunCmd(String[] shell) {
StringBuilder suc = new StringBuilder();
try {
Runtime run = Runtime.getRuntime();// 返回与当前 Java 应用程序相关的运行时对象
// OutputStream可对shell实现输入
Process p;
p = run.exec(shell);

BufferedInputStream in = new BufferedInputStream(p.getInputStream());
BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
String lineStr;
while ((lineStr = inBr.readLine()) != null) {
// 获得命令执行后在控制台的输出信息
suc.append(lineStr);
suc.append("\n");
logger.info(lineStr);
}

// 检查命令是否执行失败。
p.waitFor();
// p.exitValue(); // p.exitValue()==0表示正常结束,1:非正常结束
p.destroy();

inBr.close();
in.close();
} catch (Exception e) {
throw new RuntimeException("执行脚本错误!" + e.getLocalizedMessage(), e);
}

return suc.toString();
}

奖励园豆:5
2012 | 高人七级 |园豆:21230 | 2016-04-08 09:25

把tomcat的运行时环境使用jdk1.7.0_80,就正常了,使用jdk1.6.10,jdk1.7.0_10都存在这个问题。

泱泱 | 园豆:2 (初学一级) | 2016-04-08 09:37
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册