Java远程调用Shell脚本并获取输出信息【推荐】
1、添加依赖 <dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>262</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> 2、Api说明 首先构造一个连接器,传入一个需要登陆的ip地址;
模拟登陆目的服务器,传入用户名和密码; boolean isAuthenticated = conn.authenticateWithPassword(userName,passWord); 它会返回一个布尔值,true 代表成功登陆目的服务器,否则登陆失败。 打开一个session,执行你需要的linux 脚本命令; Session session = conn.openSession(); session.execCommand(“ifconfig”); 接收目标服务器上的控制台返回结果,读取br中的内容; InputStream stdout = new StreamGobbler(session.getStdout()); BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); 得到脚本运行成功与否的标志 :0-成功 非0-失败 System.out.println(“ExitCode: ” + session.getExitStatus()); 关闭session和connection session.close(); conn.close(); Tips: 通过第二部认证成功后当前目录就位于 3. 实例:工具类 public class SSHTool { private Connection conn; private String ipAddr; private Charset charset = StandardCharsets.UTF_8; private String userName; private String password; public SSHTool(String ipAddr,String userName,String password,Charset charset) { this.ipAddr = ipAddr; this.userName = userName; this.password = password; if (charset != null) { this.charset = charset; } } /** * 登录远程Linux主机 * * @return 是否登录成功 */ private boolean login() { conn = new Connection(ipAddr); try { // 连接 conn.connect(); // 认证 return conn.authenticateWithPassword(userName,password); } catch (IOException e) { e.printStackTrace(); return false; } } /** * 执行Shell脚本或命令 * * @param cmds 命令行序列 * @return 脚本输出结果 */ public StringBuilder exec(String cmds) throws IOException { InputStream in = null; StringBuilder result = new StringBuilder(); try { if (this.login()) { // 打开一个会话 Session session = conn.openSession(); session.execCommand(cmds); in = session.getStdout(); result = this.processStdout(in,this.charset); conn.close(); } } finally { if (null != in) { in.close(); } } return result; } /** * 解析流获取字符串信息 * * @param in 输入流对象 * @param charset 字符集 * @return 脚本输出结果 */ public StringBuilder processStdout(InputStream in,Charset charset) throws FileNotFoundException { byte[] buf = new byte[1024]; StringBuilder sb = new StringBuilder(); // OutputStream os = new FileOutputStream("./data.txt"); try { int length; while ((length = in.read(buf)) != -1) { // os.write(buf,c); sb.append(new String(buf,length)); } } catch (IOException e) { e.printStackTrace(); } return sb; } public static void main(String[] args) throws IOException { SSHTool tool = new SSHTool("192.168.100.40","root","123456",StandardCharsets.UTF_8); StringBuilder exec = tool.exec("bash /root/test12345.sh"); System.out.println(exec); } } 总结 以上所述是小编给大家介绍的Java远程调用Shell脚本并获取输出信息,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |