scp via java

前端 未结 15 779
粉色の甜心
粉色の甜心 2020-11-27 13:06

What is the best method of performing an scp transfer via the Java programming language? It seems I may be able to perform this via JSSE, JSch or the bouncy castle java libr

相关标签:
15条回答
  • 2020-11-27 13:36

    I need to copy folder recursively, after trying different solutions, finally end up by ProcessBuilder + expect/spawn

    scpFile("192.168.1.1", "root","password","/tmp/1","/tmp");
    
    public void scpFile(String host, String username, String password, String src, String dest) throws Exception {
    
        String[] scpCmd = new String[]{"expect", "-c", String.format("spawn scp -r %s %s@%s:%s\n", src, username, host, dest)  +
                "expect \"?assword:\"\n" +
                String.format("send \"%s\\r\"\n", password) +
                "expect eof"};
    
        ProcessBuilder pb = new ProcessBuilder(scpCmd);
        System.out.println("Run shell command: " + Arrays.toString(scpCmd));
        Process process = pb.start();
        int errCode = process.waitFor();
        System.out.println("Echo command executed, any errors? " + (errCode == 0 ? "No" : "Yes"));
        System.out.println("Echo Output:\n" + output(process.getInputStream()));
        if(errCode != 0) throw new Exception();
    }
    
    0 讨论(0)
  • 2020-11-27 13:37

    The openssh project lists several Java alternatives, Trilead SSH for Java seems to fit what you're asking for.

    0 讨论(0)
  • 2020-11-27 13:37

    jsCH has worked great for me. Below is an example of a method that will connect to sftp server and download files to specified directory. It is recommended to stay away from disabling StrictHostKeyChecking. Although a little bit more difficult to set up, for security reasons specifying the known hosts should be the norm.

    jsch.setKnownHosts("C:\Users\test\known_hosts"); recommended

    JSch.setConfig("StrictHostKeyChecking", "no"); - not recommended

    import com.jcraft.jsch.*;
     public void downloadFtp(String userName, String password, String host, int port, String path) {
    
    
            Session session = null;
            Channel channel = null;
            try {
                JSch ssh = new JSch();
                JSch.setConfig("StrictHostKeyChecking", "no");
                session = ssh.getSession(userName, host, port);
                session.setPassword(password);
                session.connect();
                channel = session.openChannel("sftp");
                channel.connect();
                ChannelSftp sftp = (ChannelSftp) channel;
                sftp.get(path, "specify path to where you want the files to be output");
            } catch (JSchException e) {
                System.out.println(userName);
                e.printStackTrace();
    
    
            } catch (SftpException e) {
                System.out.println(userName);
                e.printStackTrace();
            } finally {
                if (channel != null) {
                    channel.disconnect();
                }
                if (session != null) {
                    session.disconnect();
                }
            }
    
        }
    
    0 讨论(0)
  • 2020-11-27 13:38

    This is high-level solution, no need to reinvent. Quick and dirty!

    1) First, go to http://ant.apache.org/bindownload.cgi and download latest Apache Ant binary. (nowadays, apache-ant-1.9.4-bin.zip).

    2) Extract the downloaded file and find the JAR ant-jsch.jar ("apache-ant-1.9.4/lib/ant-jsch.jar"). Add this JAR in your project. Also ant-launcher.jar and ant.jar.

    3) Go to Jcraft jsch SouceForge Project and download the jar. Nowadays, jsch-0.1.52.jar. Also Add this JAR in your project.

    Now, can you easyly use into java code the Ant Classes Scp for copy files over network or SSHExec for commands in SSH servers.

    4) Code Example Scp:

    // This make scp copy of 
    // one local file to remote dir
    
    org.apache.tools.ant.taskdefs.optional.ssh.Scp scp = new Scp();
    int portSSH = 22;
    String srvrSSH = "ssh.your.domain";
    String userSSH = "anyuser"; 
    String pswdSSH = new String ( jPasswordField1.getPassword() );
    String localFile = "C:\\localfile.txt";
    String remoteDir = "/uploads/";
    
    scp.setPort( portSSH );
    scp.setLocalFile( localFile );
    scp.setTodir( userSSH + ":" + pswdSSH + "@" + srvrSSH + ":" + remoteDir );
    scp.setProject( new Project() );
    scp.setTrust( true );
    scp.execute();
    
    0 讨论(0)
  • 2020-11-27 13:40

    plug: sshj is the only sane choice! See these examples to get started: download, upload.

    0 讨论(0)
  • 2020-11-27 13:40

    -: Refining Fernando's answer a little, if you use Maven for dependency management :-

    pom.xml:

    <dependency>
      <groupId>org.apache.ant</groupId>
      <artifactId>ant-jsch</artifactId>
      <version>${ant-jsch.version}</version>
    </dependency>
    

    Add this dependency in your project. Latest version can be found here.

    Java code:

    public void scpUpload(String source, String destination) {
        Scp scp = new Scp();
        scp.setPort(port);
        scp.setLocalFile(source);
        scp.setTodir(username + ":" + password + "@" + host + ":" + destination);
        scp.setProject(new Project());
        scp.setTrust(true);
        scp.execute();
    }
    
    0 讨论(0)
提交回复
热议问题