码迷,mamicode.com
首页 > 编程语言 > 详细

使用JAVA执行shell

时间:2020-06-03 00:33:24      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:ring   buffered   result   inpu   man   结果   out   创建   数据   

引入依赖
1
<dependency> 2 <groupId>ch.ethz.ganymed</groupId> 3 <artifactId>ganymed-ssh2</artifactId> 4 <version>262</version> 5 </dependency>
创建Connection并连接
1
Connection conn = new Connection("47.112.138.184"); 2 conn.connect();
需要账号密码登录的机器,进行校验,返回布尔值
1
boolean login = conn.authenticateWithPassword(ACCOUNT, PASSWORD);
打开回话,并执行shell指令
1
Session session = conn.openSession(); 2 session.execCommand("cd /home/scripts;ls");    //多条指令时,用英文半角顿号隔开

getStdout()方法可拿到一个输入流,即远端控制台返回的数据
1 StreamGobbler gobbler = new StreamGobbler(session.getStdout());
2 BufferedReader reader = new BufferedReader(new InputStreamReader(gobbler));

 流处理
StringBuilder result = new StringBuilder(); while(true) { String readLine = reader.readLine(); if (readLine == null) { reader.close(); break; } result.append(readLine).append("\n\r"); }

 

 


getExitStatus()可获取指令执行结果,0-成功;1-失败
1 Integer exitStatus = session.getExitStatus();

切记:关闭reader、session、conn

 

 

 

 以下为完整可用的工具类
1
     Connection conn = new Connection("IP"); 2 conn.connect(); 3 boolean login = conn.authenticateWithPassword("ACCOUNT", "PASSWORD"); 4 if (login) { 5 Session session = conn.openSession(); 6 session.execCommand("cd /home/scripts;ls"); 7 StreamGobbler gobbler = new StreamGobbler(session.getStdout()); 8 BufferedReader reader = new BufferedReader(new InputStreamReader(gobbler)); 9 10 StringBuilder result = new StringBuilder(); 11 while(true) { 12 String readLine = reader.readLine(); 13 if (readLine == null) { 14 reader.close(); 15 break; 16 } 17 result.append(readLine).append("\n\r"); 18 } 19 20 Integer exitStatus = session.getExitStatus(); 21 session.close(); 22 23 System.err.println("result:"+result); 24 System.err.println("exit ? " + exitStatus); 25 } 26 27 if (conn != null) { 28 conn.close(); 29 }

 

使用JAVA执行shell

标签:ring   buffered   result   inpu   man   结果   out   创建   数据   

原文地址:https://www.cnblogs.com/yan-zm/p/13028732.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!