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();
        }
    }
}

 

深漂碼農整理,定期干貨分享,自我梳理,一同成長


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM