2011-02-08 9 views
26

나는 SFTP 통신을 위해 JSch을 사용하고 있습니다. 이제 키 기반 인증을 사용하고 싶습니다. 키는 클라이언트와 서버 컴퓨터에서 한 번 네트워크 네트워크 팀에 의해로드되고 이후의 모든 통신은 사용자 기반으로 만로드됩니다. 키.JSch를 SSH 키 기반 통신에 사용할 수 있습니까?

sftp -oPort=10022 [email protected] 

[email protected]

이 명령은 잘 작동 같은

그리고 난 프로그램이 기능을 달성 할 수있는 방법을 SFTP를,에 연결할 수있다.

JSch를 사용할 수없는 경우 다른 라이브러리를 제안 해주세요. 나는 Apache SSHD을 발견했다.

답변

68

가능합니다. 살펴보기 JSch.addIdentity(...)

이렇게하면 키를 바이트 배열이나 파일에서 읽을 수 있습니다.

import com.jcraft.jsch.Channel; 
import com.jcraft.jsch.ChannelSftp; 
import com.jcraft.jsch.JSch; 
import com.jcraft.jsch.Session; 

public class UserAuthPubKey { 
    public static void main(String[] arg) { 
     try { 
      JSch jsch = new JSch(); 

      String user = "tjill"; 
      String host = "192.18.0.246"; 
      int port = 10022; 
      String privateKey = ".ssh/id_rsa"; 

      jsch.addIdentity(privateKey); 
      System.out.println("identity added "); 

      Session session = jsch.getSession(user, host, port); 
      System.out.println("session created."); 

      // disabling StrictHostKeyChecking may help to make connection but makes it insecure 
      // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no 
      // 
      // java.util.Properties config = new java.util.Properties(); 
      // config.put("StrictHostKeyChecking", "no"); 
      // session.setConfig(config); 

      session.connect(); 
      System.out.println("session connected....."); 

      Channel channel = session.openChannel("sftp"); 
      channel.setInputStream(System.in); 
      channel.setOutputStream(System.out); 
      channel.connect(); 
      System.out.println("shell channel connected...."); 

      ChannelSftp c = (ChannelSftp) channel; 

      String fileName = "test.txt"; 
      c.put(fileName, "./in/"); 
      c.exit(); 
      System.out.println("done"); 

     } catch (Exception e) { 
      System.err.println(e); 
     } 
    } 
} 
+0

실제로 키가 없으며 네트워크 팀에서 시스템에 미리로드되어 있습니다. 이제 키나 암호없이 명령을 사용하여 서버에 연결할 수 있습니다. –

+1

* 시스템에 미리로드 된 *은'.ssh/id_rsa' 또는 그와 유사한 의미이거나 호스트의'.ssh/config'에 특별한 설정이 있거나'ssh_agent'와 같은 프로그램을 사용하고 있다는 것을 의미 할 수 있습니다 열쇠를 요구하다. 자신에게 맞는 것을 탐색하고 질문에 추가하십시오. –

+0

글쎄, 정말 도움이되었습니다. 지침에 감사드립니다. –

관련 문제