执行shell命令-JAVA

//执行shell命令和脚本

public
static String getIPByShell(String inetType) { String ifip = ""; StringBuilder sb = new StringBuilder(); String command = "/usr/sbin/ifconfig " + inetType; try { Process p = Runtime.getRuntime().exec(command); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); p.destroy(); } catch (IOException e) { e.printStackTrace(); } String ifinfo = sb.toString(); if (ifinfo.indexOf("netmask") == -1) { logger.warn("command=[{}] 没有返回 [netmask]相关的信息", command); } else { // 从netmask处截取,然后以空格拆分,最后一个值即为内网IP String[] ifinfoArr = ifinfo.substring(0, ifinfo.indexOf("netmask")).split(" "); ifip = ifinfoArr[ifinfoArr.length - 1]; } return ifip; }
/**
     * 判断操作系统是否 win 或者 mac 等个人电脑
     */
    public static boolean isPC(){
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win") || os.toLowerCase().startsWith("mac")){
            return true;
        }
        return false;
    }
/**
     * 得到公网IP
     * 
     */
    public static String getInternetIp2() {
        String ip = "";
        String chinaz = "http://ip.chinaz.com";

        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;
        try {
            url = new URL(chinaz);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            while ((read = in.readLine()) != null) {
                inputLine.append(read + "
");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Pattern p = Pattern.compile("\<dd class\="fz24">(.*?)\<\/dd>");
        Matcher m = p.matcher(inputLine.toString());
        if (m.find()) {
            String ipstr = m.group(1);
            ip = ipstr;
        }
        return ip;
    }
 
原文地址:https://www.cnblogs.com/wanhua-wu/p/13601263.html