リモート・サーバからネイティブへのファイルのコピー:SCPClientシンプル・レコードの使用

1732 ワード

一、依存

    ch.ethz.ganymed
    ganymed-ssh2
    262

二、論理実現
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SCPInputStream;

import java.io.File;
import java.io.FileOutputStream;

/**
 * @author 
 * @name
 * @desc
 * @jdk 1.8
 * @os Deepin
 * @date 2019/7/13.
 */
public class CopyFile {

    public static void main(String[] args) {
        try {
            //     ip
            String ip = "134.256.11.10";
            // ssh  
            int port = 22;
            // ssh         
            String pwd = "9857q*qCE1zbbcgc";
            String user = "root";

            //     
            Connection conn = new Connection(ip, port);
            conn.connect();
            //   
            conn.authenticateWithPassword(user, pwd);

            //   SCPClient
            SCPClient sc = conn.createSCPClient();
            //             (           )
            SCPInputStream is = sc.get("/usr/local/server/test.xml");
            //          
            FileOutputStream os = new FileOutputStream(new File("/home/bing/server/test.xml"));
            //        
            byte[] b = new byte[4096];
            int i;
            while ((i = is.read(b)) != -1) {
                os.write(b, 0, i);
            }
            os.flush();
            // copy  ,      
            is.close();
            os.close();
            conn.close();
            System.out.println("copy ok");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}