Spring Jsch java ssh 접속

2023. 12. 26. 10:58·Spring
728x90
private Session session;
private ChannelExec channelExec;

connect

public void connectSSH() throws JSchException {
  JSch jsch = new JSch();
  session = jsch.getSession(username, host, port);
  session.setPassword(password);
  session.setConfig("StrictHostKeyChecking", "no");

  session.connect();
}

connectSSH(); // ssh 연결

try {
    Channel channel = session.openChannel("exec");  // 채널 접속

    channelExec = (ChannelExec) channel; // 명령 전송 채널사용
    channelExec.setPty(true);
    channelExec.setCommand(command);

    InputStream in = channel.getInputStream();
    ((ChannelExec) channel).setErrStream(System.err);
    StreamGobbler streamGobbler = new StreamGobbler(in, messageService::send); // 웹소켓  
    Executors.newSingleThreadExecutor().submit(streamGobbler);

    channel.connect();  // 실행

    while (true) {
        if(channel.isClosed()) {
            channel.disconnect();
            break;
        }
    }

} catch (JSchException e) {
    throw new RuntimeException("Error durring SSH command execution. Command");
} catch (IOException e) {
    throw new RuntimeException(e);
} finally {
    this.disConnectSSH();
  }
}

disconnect

private void disConnectSSH() {
  if (session != null) session.disconnect();
  if (channelExec != null) channelExec.disconnect();
}
728x90
'Spring' 카테고리의 다른 글
  • Spring Batch, 배치와 스케줄러의 차이, Job, Tasklet, Chunk
  • Spring Jsch SSH Private Key, Dockerfile 복사, Jsch kubernetes pod
  • Spring @Async 비동기 처리
  • Spring websocket 웹소켓, java 채팅 프로그램
Karla Ko
Karla Ko
𝘾𝙤𝙣𝙩𝙞𝙣𝙪𝙤𝙪𝙨𝙡𝙮 𝙄𝙢𝙥𝙧𝙤𝙫𝙞𝙣𝙜, 𝘾𝙤𝙣𝙨𝙩𝙖𝙣𝙩𝙡𝙮 𝘿𝙚𝙫𝙚𝙡𝙤𝙥𝙞𝙣𝙜 𝙔𝙚𝙨!
    250x250
  • Karla Ko
    karlaLog
    Karla Ko
  • 전체
    오늘
    어제
    • Total (467)
      • Spring (19)
      • JPA (4)
      • Cloud & Architecture (15)
        • Kubernetes (5)
        • Docker (3)
        • MSA (2)
        • GCP (1)
        • AWS (4)
      • Devops (1)
      • Message Queue (4)
        • Kafka (2)
        • RabbitMQ (2)
      • Git (4)
      • DB (4)
      • Java (9)
      • Python (4)
      • CS (11)
        • OS (8)
        • Network (2)
        • Algorithm (1)
      • Coding Test (392)
        • programmers (156)
        • Graph (43)
        • DP (37)
        • Search (31)
        • Tree (13)
        • Data Structure (26)
        • Combination (12)
        • Implement (18)
        • Geedy (23)
        • Sort (7)
        • Math (21)
        • geometry (2)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    최소신장트리
    그래프
    구현
    백준
    최단거리
    프로그래머스
    자료구조
    이분탐색
    월간코드챌린지
    재귀
    큐
    Algorithm
    LIS
    구간합
    정렬
    힙
    덱
    BFS
    파이썬
    그리디
    알고리즘
    동적계획법
    스택
    조합
    트리
    플로이드워셜
    DFS
    다익스트라
    최대공약수
    DP
  • hELLO· Designed By정상우.v4.10.3
Karla Ko
Spring Jsch java ssh 접속
상단으로

티스토리툴바