2016-06-28 2 views
0

나는 아파치 mina sshd를 사용하여 Junit 테스트 목적으로 조롱 된 ssh 서버를 설정한다. 아파치 미나에 대한 문서가 상당히 명확하지 않기 때문에 테스트에서 인증 문제를 처리하는 방법을 알 수 없습니다.Junit 테스트에서 jsch.addIdentity()를 해결하는 방법은 무엇입니까?

코드 기본적으로 로컬에서 원격으로 파일을 전송할 때 Jsch를 사용하여 테스트하고 싶습니다.

public static void scpTo(String rfilePath, String lfilePath, String user, String host, String keyPath, int port) { 
    FileInputStream fis=null; 
    try { 
     while(true) { 
      String rfile = rfilePath; 
      String lfile = lfilePath; 

      JSch jsch = new JSch(); 
      jsch.addIdentity(keyPath); 
      java.util.Properties config = new java.util.Properties(); 
      config.put("StrictHostKeyChecking", "no"); 

      Session session = jsch.getSession(user, host, port); 
      session.setConfig(config); 

      session.connect(); 

      // exec 'scp -t rfile' remotely 
      String command = "scp " + " -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(!_lfile.exists()) { 
       System.err.println("Local file not existing"); 
      } 

      //check file existing 
      File _rfile = new File(rfile); 
      if (_rfile.exists()) { 
       System.out.println("Remote file already existed"); 
       break; 
      } 

      // send "C0644 filesize filename", where filename should not include '/' 
      long filesize = _lfile.length(); 
      command = "C0644 " + filesize + " "; 
      if (lfile.lastIndexOf('/') > 0) { 
       command += lfile.substring(lfile.lastIndexOf('/') + 1); 
      } else { 
       command += lfile; 
      } 
      command += "\n"; 
      out.write(command.getBytes()); 
      out.flush(); 
      if (checkAck(in) != 0) { 
       System.exit(0); 
      } 

      // send a content of lfile 
      fis = new FileInputStream(lfile); 
      byte[] buf = new byte[1024]; 
      while (true) { 
       int len = fis.read(buf, 0, buf.length); 
       if (len <= 0) break; 
       out.write(buf, 0, len); //out.flush(); 
      } 
      fis.close(); 
      fis = null; 
      // send '\0' 
      buf[0] = 0; 
      out.write(buf, 0, 1); 
      out.flush(); 
      if (checkAck(in) != 0) { 
       System.exit(0); 
      } 
      out.close(); 

      channel.disconnect(); 
      session.disconnect(); 

      //System.exit(0); 

      Thread.sleep(2000); 
     } 
    } catch (Exception e) { 
     System.out.println(e); 
     try { 
      if (fis != null) fis.close(); 
     } catch (Exception ee) { 
     } 
    } 
} 

그리고 테스트를 위해 setUp이 사용되었습니다. 내 리소스 폴더에있는 지정된 키 파일을 사용하여 모든 사용자 & 호스트 쌍을 인증하려면 setUp에 대해 어떻게해야합니까? 현재 setUp의 경우 Auth fail 오류가 발생합니다.

@Before 
public void setup() { 
    user = "siyangli"; 
    host = "localhost"; 
    //pick a port not occupied for tesing 
    port = 22998; 
    sshd = SshServer.setUpDefaultServer(); 
    sshd.setPort(port); 
    keyPath = "/Users/siyangli/.ssh/id_rsa"; 
    //it will change the key file??? do not know why, how to work around the authentication key?? 
    sshd.setKeyPairProvider(new FileKeyPairProvider(new String[]{"/Users/siyangli/.ssh/id_rsa"})); 
    //sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(keyPath)); 
    sshd.setPasswordAuthenticator(new PasswordAuthenticator() { 
     public boolean authenticate(String username, String password, ServerSession session) { 
      return true; 
     } 
    }); 
    sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() { 
     @Override 
     public boolean authenticate(String username, PublicKey key, ServerSession session) { 
      return true; 
     } 
    }); 
    CommandFactory myCommandFactory = new CommandFactory() { 
     public Command createCommand(String command) { 
      System.out.println("Command: " + command); 
      return null; 
     } 
    }; 
    sshd.setCommandFactory(new ScpCommandFactory(myCommandFactory)); 
    List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<NamedFactory<UserAuth>>(); 
    userAuthFactories.add(new UserAuthPassword.Factory()); 
    sshd.setUserAuthFactories(userAuthFactories); 
    List<NamedFactory<Command>> namedFactoryList = new ArrayList<NamedFactory<Command>>(); 
    namedFactoryList.add(new SftpSubsystem.Factory()); sshd.setSubsystemFactories(namedFactoryList); 
    try { 
     sshd.start(); 
    } catch (IOException e) { 
     System.out.println(e.getMessage()); 
     e.printStackTrace(); 
    } 
    System.out.println("Finished setup !!! "); 
} 
+0

힌트 : 귀하의 방법 scpTo는 ** ** 여러 가지로 ** 길을 가고 있습니다. 나는 로버트 마틴 (Robert Martin)이 "Clean Code"를 조사하도록 권장하거나 https://www.youtube.com/playlist?list=PLD0011D00849E1B79를 보면서 시간을 보냈다. 코드가 그렇게하면 많은 도움이 될 수있다. .. – GhostCat

답변

0

는이 라인을 변경해야 userAuthFactories.add를 (새 UserAuthPassword.Factory()); ~ userAuthFactories.add (새 UserAuthPublicKey.Factory());

관련 문제