SCPClient远程拉取文件

    在从服务器上拉取测试报告的时候,我查到了可以使用SCPClient,但是有个问题,就是这个只能拉取文件,不能拉取文件夹。不过这也是个知识点,现在我们也总结一下:

SCPClient是一个基本的java操作类,其可以从服务器复制文件到SSH-2服务器,或者从服务器上scp出文件到本地服务器;其操作的scp路径必须是存在与服务器上的,否则会报错。

1,     本地文件复制到远程目录

创建时使用的模式0600rw

   public void put(String localFile, String remoteTargetDirectory) throws IOException

    {

        put(new String[] { localFile }, remoteTargetDirectory, "0600");

    }

2从远程服务器下载一组文件到本地目录

public void get(String remoteFiles[], String localTargetDirectory) throws IOException

通过网上的介绍,我们现在想到,如果要把测试报告从远程服务器上获取下来,需要有如下的操作:

1)在本地先建立一个存放测试报告的文件夹,建立的时候先检测,文件夹是否存在,如果不存在则新建。

2)连接到远程服务器上,然后执行 “ls 报告所在的文件夹列出所有的文件。

3)按行获取出所有的文件名,并使用get函数将所有的文件拉取到本地。

经过这三步的循环操作,就能将远程服务器特定目录下的文件给复制到本地。示例代码如下:

package qataskclient;

import java.io.BufferedReader;

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

 

import ch.ethz.ssh2.Connection;

import ch.ethz.ssh2.SCPClient;

import ch.ethz.ssh2.Session;

import ch.ethz.ssh2.StreamGobbler;

 

class PullFiles{

public static void main(String[] args) 

    { 

    String user = "******"; 

    String pass = "*******"; 

    String host = "XXX.XXX.118.39"; 

     String path="sxftest";

     //建立远程连接

    Connection con = new Connection(host); 

    try { 

        con.connect(); 

        boolean isAuthed = con.authenticateWithPassword(user, pass); 

        System.out.println("isAuthed===="+isAuthed); 

        File folder = new File("d://opt//"+path);

        if (!folder.exists())

        {

            folder.mkdir();

        }

        SCPClient scpClient = con.createSCPClient(); 

        Session session = con.openSession(); 

        session.execCommand("ls /root/"+path);  //进入目录

        //显示执行命令后的信息 

        System.out.println("Here is some information about the remote host:"); 

        InputStream stdout = new StreamGobbler(session.getStdout());  

        BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); 

       

        while (true) 

        { 

            String line = br.readLine(); 

            if (line == null) 

                break; 

            scpClient.get("/root/"+path+"/"+line,"d://opt//"+path); 

            System.out.println(line); 

        } 

        System.out.println("ExitCode: " + session.getExitStatus()); 

        //关闭远程连接

        session.close(); 

        con.close();          

    } catch (IOException e) { 

        e.printStackTrace(); 

    }  

    }

}

  同样我们也可以用类似的方法现实现向服务器上传文件,根据具体的问题,稍微修改一下代码即可,所以在此我们不再给出示例代码。

原文地址:https://www.cnblogs.com/eagleking0318/p/6520746.html