자바 sftp 및 원 격 실행 명령 구현

프로젝트 에서 ActiveMQ 의 http 방식 을 sftp 방식 으로 파일 을 다운로드 하려 고 합 니 다.sftp 는 22 포트 를 개통 해 야 하기 때문에 ssh 도 사용 할 수 있 기 때문에 ssh 를 통 해 명령 을 수행 할 수 있 습 니 다.jsch - 0.1.44. jar 를 참조 하여 먼저 sftp 코드 를 직접 올 려 야 합 니 다.
package com.icbc.SFTP;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

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

public class MediaSftp {
    public Session session;
    private String usr;
    private String pwd;
    
    public MediaSftp(String usr,String pwd,String ip) throws JSchException {
    this.usr = usr;
    this.pwd=pwd;
    Connect(ip);
    }
    public void Connect(String ip) throws JSchException{  
        JSch jsch = new JSch();  
        try{
       this.session = jsch.getSession(this.usr, ip,22);
       if(session != null){  
           session.setPassword(this.pwd);
           session.setConfig("StrictHostKeyChecking","no");
           session.setTimeout(30000);
           session.connect();
           System.out.println("connect to "+ip);
           if(session != null && !session.isConnected()){                     
               this.close(); 
           }    
       } 
        }catch(JSchException e){
        throw e;
        }          
    }  
    public void close(){  
        if(session != null && session.isConnected()){  
            session.disconnect();
//            this.isConnectSSH = false;
        }else{ 
        }  
    }  
    
    public boolean download(String downloadFile,String saveFile) throws Exception{
try {
        ChannelSftp sftp = (ChannelSftp)     
        session.openChannel("sftp");
        sftp.connect(); 
        sftp.cd("/opt/activemq/apache-activemq-5.13.4/webapps/fileserver/media/");
        File file = new File(saveFile);
        System.out.println(saveFile);
        File parentFile = file.getParentFile(); 
        if(!parentFile.exists()){
              parentFile.mkdirs();
        }
        InputStream in = null;
        FileOutputStream outputStream = new FileOutputStream(file);

         in = sftp.get(downloadFile);
         //   byte          
         byte[] buffer = new byte[20480];
         int count = 0;
         while ((count = in.read(buffer)) != -1) {
               if (count == 0) break;
               outputStream.write(buffer, 0, count);
         }
         
         in.close();
         outputStream.close();
         outputStream.flush();
         sftp.disconnect();
         this.close();
         return true;
      } catch (Exception e) {
          throw e;
      }
}  
}

호출 할 때 먼저 이 종 류 를 예화 한 다음 에 다운 로드 방법 을 직접 호출 하면 됩 니 다.입 참 은 다운로드 할 파일 이름과 로 컬 에 저장 할 경로 입 니 다. 그리고 로 컬 파일 이름 을 맞 춰 download 방법 으로 들 어 갑 니 다.반환 값 은 다운로드 시간 입 니 다.
public long getMedia(String hostip,String fileName, String localPath) throws Exception  {
    MediaSftp sftp = new MediaSftp("username","passwords",hostip);
    String localFile = localPath+fileName;
    long start = System.currentTimeMillis();
    sftp.download(fileName, localFile);
    return System.currentTimeMillis()-start;
}

이 밖 에 jsch 는 원 격 ssh 프로 토 콜 로그 인 후 명령 을 수행 하 는 방법 도 제공 했다.디 렉 터 리 에 최근 에 업 데 이 트 된 파일 이름 을 가 져 오 는 명령 을 실행 하 는 방법 입 니 다. 이 방법 을 MediaSftp 클래스 에 추가 할 수 있 습 니 다. MedisSftp 클래스 를 예화 하여 연결 을 만 든 후 이 방법 을 사용 할 수 있 습 니 다.
public String getLatestFileName(String patterns) throws Exception {
//     ,                  patterns   
    String cmd = "ls -ltr /opt/activemq/apache-activemq-5.13.4/webapps/fileserver/media/|grep "+patterns+"|tail -1|awk {'print $NF'}
"; ByteArrayOutputStream retOut = new ByteArrayOutputStream(); ChannelShell channelShell = (ChannelShell)session.openChannel("shell"); PipedInputStream cmdIn = new PipedInputStream(); PipedOutputStream cmdOut = new PipedOutputStream(cmdIn); channelShell.setInputStream(cmdIn); channelShell.setOutputStream(retOut); channelShell.connect(30000); cmdOut.write(cmd.getBytes()); cmdOut.flush(); // Thread.sleep(2000); cmdOut.close(); cmdIn.close(); String retMsg = retOut.toString(); retOut.close(); channelShell.disconnect(); // , String[] retArr= retMsg.split("
"); return retArr[retArr.length-2].trim(); }

좋은 웹페이지 즐겨찾기