1,获取ip
private static String INET_TYPE_ETH0 = "eth0"; private static String INET_TYPE_PPP0 = "ppp0"; private static String INET_TYPE_PPP1 = "ppp1";
public static String getIPByShell(String inetType) { String ifip = ""; StringBuilder sb = new StringBuilder(); String command = "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; }
2,变更ip
START("adsl-start", "启动新IP"), STOP("adsl-stop", "停止新IP");
public static boolean changeIp() { logger.info("开始执行ip改变命令"); return ExecuteCmdUtil.execute(VpsAdslCmdEnum.STOP.getCmd()) && ExecuteCmdUtil.execute(VpsAdslCmdEnum.START.getCmd()); }
ExecuteCmdUtil.execute
public static boolean execute(String cmd) { logger.info("开始执行[{}]命令", cmd); boolean excRet = true; if (StringUtils.isBlank(cmd)) { logger.warn("执行命令为空"); return excRet; } InputStreamReader stdISR = null; InputStreamReader errISR = null; Process process = null; try { process = Runtime.getRuntime().exec(cmd); int exitValue = process.waitFor(); logger.info("exitValue:" + exitValue); String line = null; stdISR = new InputStreamReader(process.getInputStream()); BufferedReader stdBR = new BufferedReader(stdISR); while ((line = stdBR.readLine()) != null) { logger.info("STD line:" + line); } errISR = new InputStreamReader(process.getErrorStream()); BufferedReader errBR = new BufferedReader(errISR); while ((line = errBR.readLine()) != null) { logger.info("ERR line:" + line); } } catch (IOException | InterruptedException e) { excRet = false; logger.error("执行命令结果=[{}]", excRet, e); } finally { try { if (stdISR != null) { stdISR.close(); } if (errISR != null) { errISR.close(); } if (process != null) { process.destroy(); } } catch (IOException e) { logger.error("正式执行命令有IO异常", e); } } return excRet; }