제목 그대로 StringBuffer에 담겨있는 녀석을 SFTP로 전송해야 하는 경우를 만났습니다.
에전에 FTP로는 해결했던 적이 있는데 SFTP는 처음이라 조금 애먹지 않을까 생각했는데 좋은 라이브러리와 샘플코드를 만나서 쉽게 해결했습니다.

  1. private Boolean ftpSend(StringBuffer sb) {  
  2.   
  3.     String remotePath = "/web/geminidream";  
  4.     String filename= "test.xml";  
  5.       
  6.     JSch jsch = new JSch();  
  7.       
  8.     ArrayList<String> remoteServerIP = new ArrayList<String>();  
  9.     remoteServerIP.add("192.168.0.1");  
  10.     remoteServerIP.add("192.168.0.2");  
  11.       
  12.     for(int i=0; i<remoteServerIP.size(); i++){  
  13.           
  14.         String remoteIP = remoteServerIP.get(i);  
  15.           
  16.         try {  
  17.             log.debug("start ftp send [" +remoteIP+ "]");  
  18.             Session session = jsch.getSession("user_id", remoteIP, 22);  
  19.               
  20.             //log.debug("Session Created");  
  21.             session.setPassword("user_pw");  
  22.             java.util.Properties config = new java.util.Properties();  
  23.             config.put("StrictHostKeyChecking""no");  
  24.             session.setConfig(config);  
  25.             session.connect();  
  26.             //log.debug("Session connected");  
  27.               
  28.             //log.debug("opening channel");  
  29.             Channel channel=session.openChannel("sftp");  
  30.             channel.connect();  
  31.             ChannelSftp c=(ChannelSftp)channel;  
  32.   
  33.             c.cd(remotePath);  
  34.             //c.cd("searchQueryLog");  
  35.               
  36.             int mode=ChannelSftp.OVERWRITE;  
  37.             InputStream is = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));  
  38.             c.put(is, filename, mode);  
  39.   
  40.             c.quit();  
  41.             session.disconnect();                     
  42.             log.debug("end ftp");  
  43.         } catch(SftpException se) {  
  44.             log.debug("SftpException : " +se.fillInStackTrace());  
  45.             return false;  
  46.         } catch(Exception e){  
  47.             log.debug("Exception : " +e.fillInStackTrace());  
  48.             return false;  
  49.         }         
  50.     }  
  51.   
  52.     return true;  
  53. }  


Posted by 달빛변신
,