문제

Java 프로그래밍 언어를 통해 SCP 전송을 수행하는 가장 좋은 방법은 무엇입니까? JSSE, JSCH 또는 Bouncy Castle Java 라이브러리를 통해이를 수행 할 수있을 것 같습니다. 이 솔루션 중 어느 것도 쉬운 답변이없는 것 같습니다.

도움이 되었습니까?

해결책

나는 결국 사용했다 JSCH- 그것은 매우 간단했고 확장하는 것처럼 보였습니다 (몇 분마다 수천 파일을 잡고있었습니다).

다른 팁

플러그 : SSHJ는 유일한 제정신 선택입니다! 시작하려면이 예제를 참조하십시오. 다운로드, 업로드.

구경하다 여기

이것이 바로 개미 SCP 작업의 소스 코드입니다. "실행"방법의 코드는 그 너트와 볼트가있는 곳입니다. 이것은 필요한 것에 대한 공정한 아이디어를 제공해야합니다. 그것은 내가 믿는 JSCH를 사용합니다.

또는 Java 코드 에서이 개미 작업을 직접 실행할 수도 있습니다.

나는 약간 더 친근하게 만들기 위해 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.org/bindownload.cgi 최신 아파치 개미 바이너리를 다운로드하십시오. (요즘 Apache-ant-1.9.4-bin.zip).

2) 다운로드 된 파일을 추출하고 항아리를 찾으십시오 ant-jsch.jar ( "Apache-ant-1.9.4/lib/ant-jsch.jar"). 프로젝트 에이 항아리를 추가하십시오. 또한 ant-launcher.jar 및 ant.jar.

3) 이동 JCRAFT JSCH SOUCEFORGE 프로젝트 그리고 항아리를 다운로드하십시오. 요즘, JSCH-0.1.52.jar. 또한 프로젝트 에이 항아리를 추가하십시오.

이제 Java Code를 쉽게 사용할 수 있습니까? 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 대안을 나열하고 Java를위한 트리 노드 SSH 당신이 요구하는 것에 맞는 것 같습니다.

Zehon이라는 SCP가있는이 SFTP API를 사용합니다. 샘플 코드를 많이 사용하기 쉽습니다. 여기 사이트가 있습니다 http://www.zehon.com

나는이 솔루션을 많이 보았고 많은 솔루션을 좋아하지 않았습니다. 알려진 호스트를 식별 해야하는 성가신 단계 때문입니다. 그것과 JSCH는 SCP 명령에 비해 엄청나게 낮은 수준입니다.

나는 이것을 요구하지 않는 라이브러리를 찾았지만 묶여서 명령 줄 도구로 사용됩니다. https://code.google.com/p/scp-java-client/

소스 코드를 살펴보고 명령 줄없이 사용하는 방법을 발견했습니다. 다음은 업로드의 예입니다.

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

가장 큰 단점은 Maven Repo가 아니라는 것입니다 (내가 찾을 수있는). 그러나 사용의 용이성은 나에게 그만한 가치가 있습니다.

여기서와 마찬가지로, 나는 JSCH 라이브러리 주위에 래퍼를 썼습니다.

Way-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 Project (Apache SSHD)를 사용하여 개발합니다. 여기서 볼 수 있습니다. https://github.com/boomz/jscp또한 JAR 파일을 다운로드 할 수 있습니다 /jar 예배 규칙서. 사용하는 방법? 살펴보세요 : https://github.com/boomz/jscp/blob/master/src/main.java

JSCH는 나를 위해 훌륭하게 일했습니다. 아래는 SFTP 서버에 연결하고 파일을 지정된 디렉토리로 다운로드하는 메소드의 예입니다. StricthostKeyChecking을 비활성화하는 것을 피하는 것이 좋습니다. 설정하기가 조금 더 어렵지만 보안상의 이유로 알려진 호스트를 지정하는 것이 표준이어야합니다.

JSCH.SETKNOWHOSTS ( "C : Users Test Known_Hosts"); 추천

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

    }

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-uploading-file-remotely-via-scp.html

다른 솔루션을 시도한 후에는 폴더를 재귀 적으로 복사해야합니다. 결국 ProcessBuilder + expling/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();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top