什么是最好的方法执行一个scp转移通过Java编程语言?看来我可能能够执行这种通过对,JSch或充气城堡java库。没有这些解决方案似乎有一个简单的答案。

有帮助吗?

解决方案

我结束了使用 Jsch - 这是非常简单,似乎扩展得很好(我被抓了几千年的文件每隔几分钟)。

其他提示

插件:sshj是唯一理智的选择!看到这些例子得到启动: 下载, 上传.

我包裹Jsch一些实用的方法来使它有点友好并把它称为

Jscp

可用这里: https://github.com/willwarren/jscp

SCP实用程序来焦油的文件夹,拉链它,和SCP的某处,然后将其解压缩。

用法:

// 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") 
           );

此外,还包括有用的类 - SCP和Exec和一个TarAndGzip,这在几乎相同的方式工作

这是<强>高级别溶液下,没有必要重塑。快速和肮脏!

<强> 1)首先,访问 HTTP://ant.apache。组织/ bindownload.cgi 并下载最新版的Apache Ant安装。 (现在,apache-ant-1.9.4-bin.zip)。

<强> 2)提取所下载的文件,并找到JAR的蚁jsch.jar ( “Apache的蚂蚁1.9.4 / LIB /蚂蚁jsch.jar” )。 添加这个JAR在您的项目。也蚂蚁launcher.jar和的ant.jar。

第3)转到 Jcraft jsch SouceForge项目和下载JAR。如今, jsch-0.1。 52.jar 的。此外添加这个JAR在您的项目

现在,你能easyly使用到Java代码的蚂蚁类的 SCP 作为通过网络复制文件或 SSHExec 作为在SSH服务器的命令。

<强> 4)代码示例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();

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

我用这个SFTP API,它具有SCP称为Zehon,这是伟大的,所以容易有很多的代码示例使用。这里是该网站 http://www.zehon.com

像一些在这里,我最后写周围的JSch库的包装。

这就是所谓的方式,secshell,并托管在GitHub上:

https://github.com/objectos/way-secshell

// scp myfile.txt localhost:/tmp
File file = new File("myfile.txt");
Scp res = WaySSH.scp()
  .file(file)
  .toHost("localhost")
  .at("/tmp")
  .send();

我写了一个SCP服务器,比其他人更容易。我使用Apache MINA项目(Apache的SSHD)去发展它。你可以在这里看看: https://github.com/boomz/JSCP 您也可以从/jar目录中的jar文件。 如何使用?采取一看: https://github.com/boomz/JSCP/斑点/主/ SRC / Main.java

jsCH为我伟大的工作。下面是将连接到服务器并下载文件SFTP将指定目录的方法的例子。建议远离禁用StrictHostKeyChecking了。虽然有点更难以建立,出于安全原因指定已知主机应该是常态。

<强> jsch.setKnownHosts( “C:\ Users \用户测试\ known_hosts中”); 推荐

<强> JSch.setConfig( “StrictHostKeyChecking”, “否”); - 不推荐

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

    }

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

您可以找到在

完整代码

HTTP://faisalbhagat.blogspot。 COM / 2013/09 / java的上传文件-远程通scp.html

我需要递归复制文件夹,尝试不同的解决方案后,终于通过的ProcessBuilder落得+期望/产卵

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();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top