package com.huimv.huimvfarmnetip.utils; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @Project : huimv.shiwan * @Package : com.huimv.biosafety.uface.controller * @Description : TODO * @Version : 1.0 * @Author : ZhuoNing * @Create : 2020-12-25 **/ @Component @Slf4j public class IPUtils { /** * 执行shell脚本命令 * @param file */ public void doExec(String file) { try { Runtime.getRuntime().exec("bash " + file); log.info("bash " + file); } catch (IOException e) { log.warn("Exec " + file + " IOException:", e); } } /** * 执行一个Shell脚本 */ public boolean execute(String shellFile) { //脚本文件为NULL或空值 if (null == shellFile || shellFile.equals("")) { log.warn("ShellCommand shellFile is null."); return false; } if (log.isDebugEnabled()) { log.debug("bash " + shellFile); } try { Process process = Runtime.getRuntime().exec("bash " + shellFile); int iretCode = process.waitFor(); try { if (iretCode != 0) { BufferedReader br = new BufferedReader( new InputStreamReader(process.getErrorStream())); StringBuilder errorDesc = new StringBuilder(); for (String str = br.readLine(); str != null; str = br .readLine()) { errorDesc.append(str); } log.error("execute shell " + shellFile + " failed: " + errorDesc); //zkf35483 新增关闭流操作 br.close(); } else { return true; } } catch (IOException e) { log.error("IOException:", e); } finally { process.getErrorStream().close(); process.getInputStream().close(); process.getOutputStream().close(); } } catch (Exception e) { log.error("Execute " + shellFile + " exception:", e); } return false; } public String run(String file,String ip){ String[] shellFile = new String[]{"sh",file,ip}; try { Process ps = Runtime.getRuntime().exec(shellFile); ps.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } String result = sb.toString(); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>"+result); return result; } catch (Exception e) { e.printStackTrace(); return null; } } public String run_old(String shellFile){ try { Process ps = Runtime.getRuntime().exec(shellFile); ps.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } String result = sb.toString(); // System.out.println(result); return result; } catch (Exception e) { e.printStackTrace(); return null; } } }