使用JAVA执行shell

Posted 老YAN

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用JAVA执行shell相关的知识,希望对你有一定的参考价值。

引入依赖
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(" "); }

 

 


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(" "); 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的主要内容,如果未能解决你的问题,请参考以下文章

如何在java中执行shell脚本

java连接ssh执行shell脚本

Java 执行远程主机shell命令代码

在 JAVA 中执行 cql shell 文件或命令

java.lang.IllegalStateException:onSaveInstanceState On Activity Backpress 后无法执行此操作(不使用任何片段)

怎样在java代码中调用执行shell脚本