zoukankan      html  css  js  c++  java
  • java远程执行linux服务器上的shell脚本

    业务场景:需要从服务器A中新增的文件同步至本地服务器,服务器A中内存有限,需同步成功之后清除文件。

    Java调用远程shell脚本,需要和远程服务器建立ssh链接,再调用指定的shell脚本。

    1.创建清除文件shell脚本,可以使用touch或者vi命令

    #创建sh文件
    vi file_clear.sh
    
    #file_clear.sh内容如下
    #!/bin/bash
    #将日志定向输出到/opt/data/logs路径下,以当前日期为日志名称
    echo "执行公告数据文件清空定时任务,执行时间$(date -d "now" "+%Y-%m-%d %H:%M:%S")" 
    >> /opt/data/logs/$(date -d "now" +%Y-%m-%d).log
    #指定目标路径并删除
    find /opt/data/files/temp/ -type d | xargs rm -rf

      给file_clear.sh文件赋予可执行权限

    chmod +x file_clear.sh
    

      

    2.pom.xml中引入ganymed-ssh2依赖

    <dependency>
       <groupId>ch.ethz.ganymed</groupId>
       <artifactId>ganymed-ssh2</artifactId>
       <version>262</version>
    </dependency>

    3.新建ssh连接类SSHClient,用于与远程服务器建立连接,参数可在yml文件或者properties文件中指定

    package com.xie.api;
    
    import ch.ethz.ssh2.ChannelCondition;
    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.Session;
    import org.springframework.beans.factory.annotation.Value;
    
    import java.io.IOException;
    import java.nio.charset.Charset;
    
    public class SSHClient {
    
        private String ip;
        private String username;
        private String password;
    
        private String charset = Charset.defaultCharset().toString();
        private static final int TIME_OUT = 1000 * 5 * 60;
    
        private Connection conn;
    
        public SSHClient(String ip, String username, String password) {
            this.ip = ip;
            this.username = username;
            this.password = password;
        }
    
        /**
         * 登录指远程服务器
         * @return
         * @throws IOException
         */
        private boolean login() throws IOException {
            conn = new Connection(ip);
            conn.connect();
            return conn.authenticateWithPassword(username, password);
        }
    
        public int exec(String shell) throws Exception {
            int ret = -1;
            try {
                if (login()) {
                    Session session = conn.openSession();
                    session.execCommand(shell);
                    session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
                    ret = session.getExitStatus();
                } else {
                    throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略
                }
            } finally {
                if (conn != null) {
                    conn.close();
                }
            }
            return ret;
        }
    
        public static void main(){
            try {
                SSHClient sshClient = new SSHClient("服务器A ip", "username", "password");
                sshClient.exec("服务器shell脚本路径");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    深漂码农整理,定期干货分享,自我梳理,一同成长

    技术交流QQ群:579949017 或者添加个人微信:xieya0126 加入微信交流群
  • 相关阅读:
    Linux下通过Generic Binaries安装MySQL 5.5
    struts 2 中AJAX的使用及Struts 2 JSON的使用
    关于Abstract interface的问题。
    对于“Win8对开发者的影响”的一些看法
    RealtimeModifier Bug Report | RealtimeModifier Bug 反馈
    何为Tomcat内存
    SSH开发过程中的中文问题汇总
    Spring Test 整合 JUnit 4 使用总结
    创建Shell脚本方便MySQL服务端启动
    学习笔记 winForm move功能 与 drag 功能
  • 原文地址:https://www.cnblogs.com/dsxie/p/12675065.html
Copyright © 2011-2022 走看看