簡體   English   中英

SSH到遠程服務器並在Springboot中讀取文件

[英]SSH to remote server and read Files in Springboot

我只需要知道在 Spring 啟動時是否可能出現以下情況?

假設我需要ssh到服務器並在springboot中的特定目錄中進行操作。 例如,我只需要在 spring 啟動應用程序中讀取服務器 192.xxx.xxx.xxx 主目錄中的文件。 如果可能,如何在 application.properties 中設置服務器憑據(登錄用戶、密碼)。

需要您的關注。 任何幫助將不勝感激。

謝謝你。

是的,有可能。

有一個名為 JSch 的庫 - Java 安全通道 ( http://www.jcraft.com/jsch/ )。

這是您連接到遠程主機的方式:

private static final String REMOTE_HOST = "0.0.0.0";
private static final String USERNAME = "";
private static final String PASSWORD = "";
private static final int REMOTE_PORT = 22;
private static final int SESSION_TIMEOUT = 10000;
private static final int CHANNEL_TIMEOUT = 5000;

private void readFile() {
    String remoteFile = "/your/path/file.txt";
    Session jschSession = null;

    try {
        JSch jsch = new JSch();

        jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);

        jschSession.setPassword(PASSWORD);
        jschSession.connect(SESSION_TIMEOUT);

        Channel sftp = jschSession.openChannel("sftp");
        sftp.connect(CHANNEL_TIMEOUT);
        ChannelSftp channelSftp = (ChannelSftp) sftp;

        InputStream stream = channelSftp.get(remoteFile);
        
        //Parsing your file or etc. here

        channelSftp.exit();

    } catch (JSchException | SftpException e) {

        e.printStackTrace();

    } finally {
        if (jschSession != null) {
            jschSession.disconnect();
        }
    }
}

至於如何從 application.properties 設置憑據,可以使用注解:

@Configuration
@ConfigurationProperties(prefix = "mail")
public class ConfigProperties {
    
    private String hostName;
    private int port;
    private String from;

    // standard getters and setters
}

application.properties 中的示例:

mail.hostname=host@mail.com
mail.port=9000
mail.from=mailer@mail.com

進一步的解釋可以在這里找到: https://www.baeldung.com/configuration-properties-in-spring-boot

我希望它有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM