使用JAVA执行shell
2020-12-26 22:28
标签:ring buffered result inpu man 结果 out 创建 数据 切记:关闭reader、session、conn 使用JAVA执行shell 标签:ring buffered result inpu man 结果 out 创建 数据 原文地址:https://www.cnblogs.com/yan-zm/p/13028732.html引入依赖
1 dependency>
2 groupId>ch.ethz.ganymedgroupId>
3 artifactId>ganymed-ssh2artifactId>
4 version>262version>
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();
以下为完整可用的工具类
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 }