zoukankan      html  css  js  c++  java
  • 使用Java语言,连接linux服务器,并远程执行shell 脚本

    依赖:

     1 <dependency>
     2             <groupId>ch.ethz.ganymed</groupId>
     3             <artifactId>ganymed-ssh2</artifactId>
     4             <version>build210</version>
     5         </dependency>
     6  
     7         <dependency>
     8             <groupId>org.apache.directory.studio</groupId>
     9             <artifactId>org.apache.commons.lang</artifactId>
    10             <version>2.6</version>
    11  </dependency>
      1 package com.lwl.controller;
      2 
      3 import ch.ethz.ssh2.Connection;
      4 import ch.ethz.ssh2.Session;
      5 import ch.ethz.ssh2.StreamGobbler;
      6 import com.test.controller.Script;
      7 import org.apache.commons.lang.StringUtils;
      8 import org.springframework.stereotype.Controller;
      9 import org.springframework.web.bind.annotation.RequestMapping;
     10 
     11 import javax.servlet.http.HttpServletRequest;
     12 import javax.servlet.http.HttpServletResponse;
     13 import java.io.*;
     14 
     15 /**
     16  * @author liuwenlong
     17  * @create 2021-11-08 20:42:07
     18  */
     19 @SuppressWarnings("all")
     20 @Controller
     21 @RequestMapping(value = "server")
     22 public class ConnectServerController {
     23 
     24     //字符编码默认是utf-8
     25     private static String DEFAULTCHART = "UTF-8";
     26     private Connection conn;
     27     private String ip;
     28     private String userName;
     29     private String userPwd;
     30 
     31     public ConnectServerController(String ip, String userName, String userPwd) {
     32         this.ip = ip;
     33         this.userName = userName;
     34         this.userPwd = userPwd;
     35     }
     36 
     37 
     38     public ConnectServerController() {
     39 
     40     }
     41 
     42     /**
     43      * 远程登录linux的主机
     44      *
     45      * @return 登录成功返回true,否则返回false
     46      * @author 47      * @since V0.1
     48      */
     49     public Boolean login() {
     50         boolean flg = false;
     51         try {
     52             conn = new Connection(ip);
     53             conn.connect();//连接
     54             flg = conn.authenticateWithPassword(userName, userPwd);//认证
     55         } catch (IOException e) {
     56             e.printStackTrace();
     57         }
     58         return flg;
     59     }
     60 
     61     /**
     62      * @param cmd 即将执行的命令
     63      * @return 命令执行完后返回的结果值
     64      * @author 65      * 远程执行shll脚本或者命令
     66      * @since V0.1
     67      */
     68     public String execute(String cmd) {
     69         String result = "";
     70         try {
     71             if (login()) {
     72                 Session session = conn.openSession();//打开一个会话
     73                 session.execCommand(cmd);//执行命令
     74                 result = processStdout(session.getStdout(), DEFAULTCHART);
     75                 //如果为得到标准输出为空,说明脚本执行出错了
     76                 if (StringUtils.isBlank(result)) {
     77                     result = processStdout(session.getStderr(), DEFAULTCHART);
     78                 }
     79                 conn.close();
     80                 session.close();
     81             }
     82         } catch (IOException e) {
     83             e.printStackTrace();
     84         }
     85         return result;
     86     }
     87 
     88 
     89     /**
     90      * @param cmd 即将执行的命令
     91      * @return 命令执行成功后返回的结果值,如果命令执行失败,返回空字符串,不是null
     92      * @author 93      * 远程执行shll脚本或者命令
     94      * @since V0.1
     95      */
     96     public String executeSuccess(String cmd) {
     97         String result = "";
     98         try {
     99             if (login()) {
    100                 Session session = conn.openSession();//打开一个会话
    101                 session.execCommand(cmd);//执行命令
    102                 result = processStdout(session.getStdout(), DEFAULTCHART);
    103                 conn.close();
    104                 session.close();
    105             }
    106         } catch (IOException e) {
    107             e.printStackTrace();
    108         }
    109         return result;
    110     }
    111 
    112     /**
    113      * 解析脚本执行返回的结果集
    114      *
    115      * @param in      输入流对象
    116      * @param charset 编码
    117      * @return 以纯文本的格式返回
    118      * @author119      * @since V0.1
    120      */
    121     private String processStdout(InputStream in, String charset) {
    122         InputStream stdout = new StreamGobbler(in);
    123         StringBuffer buffer = new StringBuffer();
    124         ;
    125         try {
    126             BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
    127             String line = null;
    128             while ((line = br.readLine()) != null) {
    129                 buffer.append(line + "\n");
    130             }
    131         } catch (UnsupportedEncodingException e) {
    132             e.printStackTrace();
    133         } catch (IOException e) {
    134             e.printStackTrace();
    135         }
    136         return buffer.toString();
    137     }
    138 
    139     public static void setCharset(String charset) {
    140         DEFAULTCHART = charset;
    141     }
    142 
    143     public Connection getConn() {
    144         return conn;
    145     }
    146 
    147     public void setConn(Connection conn) {
    148         this.conn = conn;
    149     }
    150 
    151     public String getIp() {
    152         return ip;
    153     }
    154 
    155     public void setIp(String ip) {
    156         this.ip = ip;
    157     }
    158 
    159     public String getUserName() {
    160         return userName;
    161     }
    162 
    163     public void setUserName(String userName) {
    164         this.userName = userName;
    165     }
    166 
    167     public String getUserPwd() {
    168         return userPwd;
    169     }
    170 
    171     public void setUserPwd(String userPwd) {
    172         this.userPwd = userPwd;
    173     }
    174 
    175     /**
    176      * 连接服务器,执行命令
    177      *
    178      * @param command
    179      * @param resp
    180      * @param req
    181      * @throws IOException
    182      */
    183     @RequestMapping(value = "server")
    184     public void server(String command, HttpServletResponse resp, HttpServletRequest req) throws IOException {
    185         Script rec = new Script("服务器IP", "账号", "密码");
    186         resp.setContentType("text/plain; charset=UTF-8");
    187         resp.setCharacterEncoding("UTF-8");
    188         PrintWriter out = resp.getWriter();
    189         command = command.trim();
    190         System.out.println("指令:" + command);
    191         //执行命令
    192         String result = rec.execute(command);
    193         System.out.println(result);
    194         out.print(result);
    195         //System.out.println(rec.execute("/usr/ksybak/myshell/tomcat-fw.sh"));
    196         //执行脚本
    197         //rec.execute("sh /usr/local/tomcat/bin/statup.sh");
    198         //这个方法与上面最大的区别就是,上面的方法,不管执行成功与否都返回,
    199         //这个方法呢,如果命令或者脚本执行错误将返回空字符串
    200         //System.out.println(rec.executeSuccess("ifconfig"));
    201     }
    202 }

    运行结果

    原创文章,转载请说明出处,谢谢合作
  • 相关阅读:
    2019-2020-1 20175301 20175305 20175318 实验三 实时系统
    2019-2020-2-20175301 20175305 20175318-实验二固件程序设计
    2019-2020-1 20175301 20175305 20175318 实验一 开发环境的熟悉
    2019-2020-1 20175305 《信息安全系统设计基础》第4周学习总结
    20175305 《信息安全系统设计基础》第1-2周学习总结
    2018-2019-2 20175305 实验五《网络编程与安全》实验报告
    2018-2019-2 20175305实验四《Android程序设计》实验报告
    20175305张天钰《java程序设计》第十一周学习总结
    使用 JDK11 遇到的问题
    Oracle 从 dual 表中查询返回多行记录
  • 原文地址:https://www.cnblogs.com/lwl80/p/15526743.html
Copyright © 2011-2022 走看看