sftp 에서 Liux 서버 에 파일 업로드 (ssh 인증)

필요: 이전에 서버 에 설정 파일 을 수 동 으로 업로드 한 다음 에 다른 서버 에 수 동 으로 복사 한 다음 에 SSH Secure File Transfer Client 클 라 이언 트 에 로그 인하 여 관련 셸 명령 번 호 를 실행 해 야 합 니 다. 현재 이 작업 은 한 키 로 완료 해 야 합 니 다. 즉, 파일 을 다른 서버 로 복사 하고 ssh 클 라 이언 트 에 로그 인하 여 사용 자 를 전환 하고 가 져 오기 명령 행 해결 방법 을 실행 해 야 합 니 다.
  • 응용 프로그램 이 있 는 기계 사용자 이름과 비밀 번 호 를 얻 은 다음 셸 스 크 립 트 를 실행 합 니 다. 이 동작 은 사용 되 지 않 았 습 니 다. 서버 의 사용자 이름과 비밀 번 호 를 제공 하지 않 기 때 문 입 니 다
  • 다른 서버 에 직접 연결 하여 복사 파일 을 실행 한 다음 셸 스 크 립 트 (취) 를 실행 하여 Liux 서버 에 파일 을 업로드 하려 면 FTP 프로 토 콜 을 사용 합 니 다. 회사 Liux 서버 에 ftp 클 라 이언 트 가 안전 검증 이 필요 하고 번 거 로 우 므 로 sftp 를 사용 하여 해결 하려 고 합 니 다. sftp 는 ssh 기반 보안 프로 토 콜 의 ftp 프로 토 콜 입 니 다.자바 에는 서버 연결 을 위 한 JSH 패키지 가 있 습 니 다.

  • 첫 번 째: JSH 가방 을 다운로드 합 니 다. 홈 페이지 에서 다운로드 하 십시오.http://www.jcraft.com/jsch/ 두 번 째 단계: 새 FtpsFileList. java 파일
    //      ,          
    public class FtpsFileList {
         
        private static final Logger LOG = LoggerFactory.getLogger(FtpsFileList.class);
    
        //    dirFile              desFile    
        public static void loadFile(String host, int port, String username, final String password, String dirFile,String desFile) {
            ChannelSftp sftp = null;
            Channel channel = null;
            Session sshSession = null;
            try {
                JSch jsch = new JSch();//    jsch  
                jsch.getSession(username, host, port);
                //      ,  ip,      Session  
                sshSession = jsch.getSession(username, host, port);
                //    
                sshSession.setPassword(password);
                Properties sshConfig = new Properties();
                sshConfig.put("StrictHostKeyChecking", "no");
                //  Session    properties
                sshSession.setConfig(sshConfig);
                sshSession.connect();
                LOG.debug("Session connected!");
                //   SFTP  
                channel = sshSession.openChannel("sftp");
                //   SFTP     
                channel.connect();
                LOG.debug("Channel connected!");
                sftp = (ChannelSftp) channel;
    
                //InputStream is = sftp.get("/ftp/re/20140713.dat");
                InputStream fis = new FileInputStream(new File(dirFile));
                //    (  inputstream    )    https://www.cnblogs.com/longyg/archive/2012/06/25/2556576.html
                sftp.put(fis,desFile);
                LOG.info("          !\r");
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeChannel(sftp);
                closeChannel(channel);
                closeSession(sshSession);
            }
        }
    
        private static void closeChannel(Channel channel) {
            if (channel != null) {
                if (channel.isConnected()) {
                    channel.disconnect();
                }
            }
        }
    
        private static void closeSession(Session session) {
            if (session != null) {
                if (session.isConnected()) {
                    session.disconnect();
                }
            }
        }
    }

    호출 방식:
    FtpsFileList.loadFile("10.31.92.70", 22, "serviceop", "115LbUrAbEsZw","/nfsc/qhcs-ansir-stg1/ansir/HanLP/xiaodai/loan-freebase.ttl","/wls/serviceop/virtuoso_script/loanXD.ttl");
    logger.info("ttl      ");

    이 단계 에 이 르 러 Liux 서버 에 파일 을 업로드 하 는 세 번 째 단계 가 완료 되 었 습 니 다. 셸 스 크 립 트 (핵심) 를 작성 하 는 것 입 니 다. 이 단계 에서 많은 것 을 배 웠 는데 셸 명령 이 매우 재 미 있 는 것 을 발 견 했 습 니 다.
    #!/usr/bin/expect
    spawn ssh serviceop@10.31.92.70
    set timeout 2
    expect "password:"
    send "115LbUrAbEsZw\r"
    expect "*]#"
    set password "wuxin952"
    spawn su root
    expect "password:"  
    send "wuxin952\r" 
    expect "#"
    send "/wls/serviceop/virtuoso-opensource/home/bin/isql localhost:13002\r" 
    send "DB.DBA.TTLP_MT(file_to_string_output('/wls/serviceop/virtuoso_script/loan.ttl'),'','http://www.xiaowei.com');\r"
    interact

    설명: 비밀 번 호 를 대화 식 으로 입력 해 야 하기 때문에 expect 명령 환경 을 사용 하여 구체 적 인 해석 을 수행 하 십시오.
    네 번 째 단계: 자바 코드 는 셸 스 크 립 트 를 호출 합 니 다. 코드 는 다음 과 같 습 니 다. Process 류 는 추상 적 인 클래스 입 니 다. 로 컬 프로 세 스 를 정의 하 는 데 사 용 됩 니 다. Runtime. getRuntime (). exec (sh) 는 프로 세 스 대상 을 되 돌려 줍 니 다.
    //     shell   
    Process ps1=Runtime.getRuntime().exec("chmod 777 /nfsc/qhcs-ansir-stg1/ansir/HanLP/xiaodai/bash_scp.sh");
    //         ,    process          
    ps1.waitFor();
    logger.info("chmod      ");
    
    BufferedReader br1 = new BufferedReader(new InputStreamReader(ps1.getInputStream()));
    while ((line = br1.readLine()) != null) {
        logger.info("chmod    :"+line);
    }
    //      expect   
    Process ps2=Runtime.getRuntime().exec("expect /nfsc/qhcs-ansir-stg1/ansir/HanLP/xiaodai/bash_scp.sh");
    ps2.waitFor();
    logger.info("expect      ");
    
    BufferedReader br2 = new BufferedReader(new InputStreamReader(ps2.getInputStream()));
    while ((line = br2.readLine()) != null) {
        logger.info("expect    :"+line);
    }
    
    String result = sb.toString();
    logger.info("expect     :"+result);

    후속 셸 명령 은 다음 블 로 그 를 보십시오

    좋은 웹페이지 즐겨찾기