Java SSH獲取服務器文件內容

需要導入jar:j2ssh-core-0.2.9.jar

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;

import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;

public class GetMes {

    public void getMessage(String path) {
        String ip = "";
        String catalogue = "";
        String filename = "";
        ip = path.substring(0, path.indexOf("#"));
        catalogue = path.substring(path.indexOf("#") + 1, path.lastIndexOf("/") + 1);
        filename = path.substring(path.lastIndexOf("/") + 1);
        SshClient client = new SshClient();
        try {
            client.connect(ip, 22);
            // 設置用戶名和密碼
            PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
            pwd.setUsername("a");
            pwd.setPassword("a");
            int result = client.authenticate(pwd);
            if (result == AuthenticationProtocolState.COMPLETE) {// 如果連接完成
                OutputStream os = new FileOutputStream("d:/mail/" + filename);
                client.openSftpClient().get(catalogue + filename, os);
                File file = new File("d:/mail/" + filename);
                if (!file.exists()) {
                    file.createNewFile();
                }
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader(file));
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e1) {
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // 這裏的path是我自己約定的ip#catalogue的形式,
        // 如果形式不同,方法體截取的方法只需做對應的修改即可。
        String path = "10.100.133.11#/app/a.txt";
        GetMes get = new GetMes();
        get.getMessage(path);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章