通过java scp

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/199624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:14:52  来源:igfitidea点击:

scp via java

javascpbouncycastlejssejsch

提问by Lloyd Meinholz

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 libraries. None of these solutions seem to have an easy answer.

通过 Java 编程语言执行 scp 传输的最佳方法是什么?看来我可以通过 JSSE、JSch 或充气城堡 Java 库来执行此操作。这些解决方案似乎都没有一个简单的答案。

采纳答案by Tim Howland

I ended up using Jsch- it was pretty straightforward, and seemed to scale up pretty well (I was grabbing a few thousand files every few minutes).

我最终使用了Jsch- 它非常简单,并且似乎扩展得很好(我每隔几分钟就会抓取几千个文件)。

回答by Kyle Burton

The openssh projectlists several Java alternatives, Trilead SSH for Javaseems to fit what you're asking for.

OpenSSH的项目列出几个Java的替代品,三铅SSH的Java似乎符合你要求的。

回答by abarax

Take a lookhere

看看这里

That is the source code for Ants' SCP task. The code in the "execute" method is where the nuts and bolts of it are. This should give you a fair idea of what is required. It uses JSch i believe.

那是 Ants 的 SCP 任务的源代码。“execute”方法中的代码是它的具体细节所在。这应该让您对需要什么有一个公平的了解。我相信它使用 JSch。

Alternatively you could also directly execute this Ant task from your java code.

或者,您也可以直接从您的 Java 代码执行此 Ant 任务。

回答by Tim Howland

I use this SFTP API which has SCP called Zehon, it's great, so easy to use with a lot of sample code. Here is the site http://www.zehon.com

我使用这个 SFTP API,它有一个名为 Zehon 的 SCP,它很棒,很容易使用很多示例代码。这是网站http://www.zehon.com

回答by shikhar

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

插件:sshj 是唯一明智的选择!请参阅以下示例以开始使用:下载上传

回答by Will

I wrapped Jsch with some utility methods to make it a bit friendlier and called it

我用一些实用方法包裹了 Jsch 使它更友好一些并称之为

Jscp

Jscp

Available here: https://github.com/willwarren/jscp

可在此处获得:https: //github.com/willwarren/jscp

SCP utility to tar a folder, zip it, and scp it somewhere, then unzip it.

SCP 实用程序,用于对文件夹进行 tar 压缩、压缩,然后将其 scp 到某处,然后解压缩。

Usage:

用法:

// create secure context
SecureContext context = new SecureContext("userName", "localhost");

// set optional security configurations.
context.setTrustAllHosts(true);
context.setPrivateKeyFile(new File("private/key"));

// Console requires JDK 1.7
// System.out.println("enter password:");
// context.setPassword(System.console().readPassword());

Jscp.exec(context, 
           "src/dir",
           "destination/path",
           // regex ignore list 
           Arrays.asList("logs/log[0-9]*.txt",
           "backups") 
           );

Also includes useful classes - Scp and Exec, and a TarAndGzip, which work in pretty much the same way.

还包括有用的类 - Scp 和 Exec,以及 TarAndGzip,它们的工作方式几乎相同。

回答by boomz

I wrote an scp server which is much easier than others. I use Apache MINA project (Apache SSHD) to develop it. You can take a look here: https://github.com/boomz/JSCPAlso you can download the jar file from /jardirectory. How to use? Take a look on: https://github.com/boomz/JSCP/blob/master/src/Main.java

我写了一个比其他人容易得多的 scp 服务器。我使用 Apache MINA 项目(Apache SSHD)来开发它。您可以在这里查看:https: //github.com/boomz/JSCP您也可以从/jar目录下载 jar 文件。如何使用?看看:https: //github.com/boomz/JSCP/blob/master/src/Main.java

回答by faisalbhagat

JSch is a nice library to work with. It has quite an easy answer for your question.

JSch 是一个很好的库。对于您的问题,它有一个非常简单的答案。

JSch jsch=new JSch();
  Session session=jsch.getSession(user, host, 22);
  session.setPassword("password");


  Properties config = new Properties();
  config.put("StrictHostKeyChecking","no");
  session.setConfig(config);
  session.connect();

  boolean ptimestamp = true;

  // exec 'scp -t rfile' remotely
  String command="scp " + (ptimestamp ? "-p" :"") +" -t "+rfile;
  Channel channel=session.openChannel("exec");
  ((ChannelExec)channel).setCommand(command);

  // get I/O streams for remote scp
  OutputStream out=channel.getOutputStream();
  InputStream in=channel.getInputStream();

  channel.connect();

  if(checkAck(in)!=0){
    System.exit(0);
  }

  File _lfile = new File(lfile);

  if(ptimestamp){
    command="T "+(_lfile.lastModified()/1000)+" 0";
    // The access time should be sent here,
    // but it is not accessible with JavaAPI ;-<
    command+=(" "+(_lfile.lastModified()/1000)+" 0\n");
    out.write(command.getBytes()); out.flush();
    if(checkAck(in)!=0){
      System.exit(0);
    }
  }

You can find complete code at

您可以在以下位置找到完整的代码

http://faisalbhagat.blogspot.com/2013/09/java-uploading-file-remotely-via-scp.html

http://faisalbhagat.blogspot.com/2013/09/java-uploading-file-remotely-via-scp.html

回答by Daniel Kaplan

I looked at a lot of these solutions and didn't like many of them. Mostly because the annoying step of having to identify your known hosts. That and JSCH is at a ridiculously low level relative to the scp command.

我看了很多这些解决方案,但并不喜欢其中的很多。主要是因为必须识别已知主机的烦人步骤。这和 JSCH 相对于 scp 命令处于低得离谱的水平。

I found a library that doesn't require this but it's bundled up and used as a command line tool. https://code.google.com/p/scp-java-client/

我找到了一个不需要这个的库,但它被捆绑起来用作命令行工具。 https://code.google.com/p/scp-java-client/

I looked through the source code and discovered how to use it without the command line. Here's an example of uploading:

我查看了源代码并发现了如何在没有命令行的情况下使用它。下面是一个上传示例:

    uk.co.marcoratto.scp.SCP scp = new uk.co.marcoratto.scp.SCP(new uk.co.marcoratto.scp.listeners.SCPListenerPrintStream());
    scp.setUsername("root");
    scp.setPassword("blah");
    scp.setTrust(true);
    scp.setFromUri(file.getAbsolutePath());
    scp.setToUri("root@host:/path/on/remote");
    scp.execute();

The biggest downside is that it's not in a maven repo (that I could find). But, the ease of use is worth it to me.

最大的缺点是它不在 Maven 仓库中(我可以找到)。但是,易用性对我来说是值得的。

回答by Eduardo Dennis

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 对我很有用。下面是连接到 sftp 服务器并将文件下载到指定目录的方法示例。建议远离禁用 StrictHostKeyChecking。虽然设置起来有点困难,但出于安全原因,指定已知主机应该是常态。

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

jsch.setKnownHosts("C:\Users\test\known_hosts"); 受到推崇的

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

JSch.setConfig("StrictHostKeyChecking", "no"); - 不建议

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();
            }
        }

    }