1 packagecom.pasier.xxx.util; 2 3 importjava.io.IOException; 4 importjava.io.InputStream; 5 importjava.nio.charset.Charset; 6 7 importorg.slf4j.Logger; 8 importorg.slf4j.LoggerFactory; 9 10 importch.ethz.ssh2.ChannelCondition; 11 importch.ethz.ssh2.Connection; 12 importch.ethz.ssh2.Session; 13 importch.ethz.ssh2.StreamGobbler; 14 15 public classRmtShellExecutor { 16 17 private static final Logger LOG = LoggerFactory.getLogger(RmtShellExecutor.class); 18 19 privateConnection conn; 20 privateString ip; 21 privateString usr; 22 privateString psword; 23 private String charset =Charset.defaultCharset().toString(); 24 25 private static final int TIME_OUT = 1000 * 5 * 60; 26 27 publicRmtShellExecutor(String ip, String usr, String ps) { 28 this.ip =ip; 29 this.usr =usr; 30 this.psword =ps; 31 } 32 33 private boolean login() throwsIOException { 34 conn = newConnection(ip); 35 conn.connect(); 36 returnconn.authenticateWithPassword(usr, psword); 37 } 38 39 public String exec(String cmds) throwsIOException { 40 InputStream stdOut = null; 41 InputStream stdErr = null; 42 String outStr = ""; 43 String outErr = ""; 44 int ret = -1; 45 46 try{ 47 if(login()) { 48 Session session =conn.openSession(); 49 session.execCommand(cmds); 50 stdOut = newStreamGobbler(session.getStdout()); 51 outStr =processStream(stdOut, charset); 52 LOG.info("caijl:[INFO] outStr=" +outStr); 53 stdErr = newStreamGobbler(session.getStderr()); 54 outErr =processStream(stdErr, charset); 55 LOG.info("caijl:[INFO] outErr=" +outErr); 56 session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT); 57 ret =session.getExitStatus(); 58 59 } else{ 60 LOG.error("caijl:[INFO] ssh2 login failure:" +ip); 61 throw new IOException("SSH2_ERR"); 62 } 63 64 } finally{ 65 if (conn != null) { 66 conn.close(); 67 } 68 if (stdOut != null) 69 stdOut.close(); 70 if (stdErr != null) 71 stdErr.close(); 72 } 73 74 returnoutStr; 75 } 76 77 private String processStream(InputStream in, String charset) throwsIOException { 78 byte[] buf = new byte[1024]; 79 StringBuilder sb = newStringBuilder(); 80 while (in.read(buf) != -1) { 81 sb.append(newString(buf, charset)); 82 } 83 returnsb.toString(); 84 } 85 86 public static voidmain(String[] args) { 87 88 String usr = "root"; 89 String password = "12345"; 90 String serverIP = "11.22.33.xx"; 91 String shPath = "/root/ab.sh"; 92 93 RmtShellExecutor exe = newRmtShellExecutor(serverIP, usr, password); 94 95 String outInf; 96 97 try{ 98 outInf = exe.exec("sh " + shPath + " xn"); 99 System.out.println("outInf= " +outInf); 100 } catch(IOException e) { 101 e.printStackTrace(); 102 } 103 } 104 105 }
java执行linux shell命令,并拿到返回值
免责声明:文章转载自《java执行linux shell命令,并拿到返回值》仅用于学习参考。如对内容有疑问,请及时联系本站处理。
上篇jeecg下实现自动默认模糊查询服务器安装node全教程下篇
宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=