Java-执行shell命令

Java-执行shell命令

1、本地调用

 1 import ch.ethz.ssh2.Connection;
 2 import ch.ethz.ssh2.Session;
 3 import lombok.extern.slf4j.Slf4j;
 4 import org.springframework.util.StringUtils;
 5 
 6 import java.io.BufferedReader;
 7 import java.io.IOException;
 8 import java.io.InputStream;
 9 import java.io.InputStreamReader;
10 
11 /**
12  * Java执行Linux命令工具类
13  *
14  * @author zy
15  * @date 2020-07-15 11:12
16  */
17 @Slf4j
18 public class LinuxUtil {
19 
20 
21     /**
22      * Java执行Linux命令(本地调用)
23      *
24      * @param command 命令
25      * @return 是否调用成功
26      */
27     public static boolean linuxOperate(String command) {
28         boolean result = false;
29         try {
30             Process proc = Runtime.getRuntime().exec(command);
31             String inStr = consumeInputStream(proc.getInputStream());
32             // 标准错误流(必须写在 waitFor 之前)
33             String errStr = consumeInputStream(proc.getErrorStream());
34 
35             int retCode = proc.waitFor();
36             if (retCode == 0 || StringUtils.isEmpty(errStr)) {
37                 log.info("==========程序正常结束==========");
38                 result = true;
39             }
40             result = true;
41         } catch (IOException e) {
42             e.printStackTrace();
43         } catch (InterruptedException e) {
44             e.printStackTrace();
45         }
46         return result;
47     }
48 
49 
50     /**
51      * 消费输入流信息
52      *
53      * @param is 输入流
54      * @return 输出结果
55      */
56     public static String consumeInputStream(InputStream is) {
57         try {
58             BufferedReader br = new BufferedReader(new InputStreamReader(is));
59             String s;
60             StringBuilder sb = new StringBuilder();
61             while ((s = br.readLine()) != null) {
62                 System.out.println(s);
63                 sb.append(s);
64             }
65             br.close();
66             is.close();
67             return sb.toString();
68         } catch (IOException e) {
69             e.printStackTrace();
70         }
71         return null;
72     }
73 
74 }
本地调用

 

2、远程调用

  远程调用需要连接远程服务(ssh连接)。

1、依赖

    <!--SSH2连接服务器执行Linux命令-->
        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>262</version>
        </dependency>      

2、代码

 1 package com.ifreegroup.releaseserver.util;
 2 
 3 
 4 import ch.ethz.ssh2.Connection;
 5 import ch.ethz.ssh2.Session;
 6 import lombok.extern.slf4j.Slf4j;
 7 import org.springframework.util.StringUtils;
 8 
 9 import java.io.BufferedReader;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.InputStreamReader;
13 
14 /**
15  * Java执行Linux命令工具类
16  *
17  * @author zy
18  * @date 2020-07-15 11:12
19  */
20 @Slf4j
21 public class LinuxUtil {
22 
23     /**
24      * Java执行Linux命令(远程调用)
25      *
26      * @param userName 用户名
27      * @param password 密码
28      * @param ip       ip地址
29      * @param command  命令
30      */
31     public static boolean linuxOperate(String userName, String password, String ip, String command) {
32         boolean result = false;
33         try {
34             //创建连接
35 //            Connection conn = new Connection(ip, port);
36             Connection conn = new Connection(ip);
37             //连接服务器
38             conn.connect();
39             //用户登陆
40             boolean isconn = conn.authenticateWithPassword(userName, password);
41             if (!isconn) {
42                 log.error("==========用户名或者密码不正确!==========");
43             } else {
44                 log.info("==========连接成功!==========");
45             }
46             //创建回话
47             Session session = conn.openSession();
48             //创建命令
49             session.execCommand(command);
50             //
51             String inStr = consumeInputStream(session.getStdout());
52             String errorStr = consumeInputStream(session.getStderr());
53             log.info("=========={}==========", inStr);
54             log.error("=========={}==========", errorStr);
55             if (StringUtils.isEmpty(errorStr)) {
56                 result = true;
57             }
58             session.close();
59             conn.close();
60         } catch (IOException e) {
61             e.printStackTrace();
62         }
63         return result;
64     }
65 
66 
67     /**
68      * 消费输入流信息
69      *
70      * @param is 输入流
71      * @return 输出结果
72      */
73     public static String consumeInputStream(InputStream is) {
74         try {
75             BufferedReader br = new BufferedReader(new InputStreamReader(is));
76             String s;
77             StringBuilder sb = new StringBuilder();
78             while ((s = br.readLine()) != null) {
79                 System.out.println(s);
80                 sb.append(s);
81             }
82             br.close();
83             is.close();
84             return sb.toString();
85         } catch (IOException e) {
86             e.printStackTrace();
87         }
88         return null;
89     }
90 
91 }
远程调用

 

posted @ 2020-07-16 17:27  趙楊  阅读(519)  评论(0编辑  收藏  举报