Java로 ssh 접속 및 command 실행

송준희·2021년 6월 21일
1

Java로 SSH로 접속하여 명령어를 실행하는 단계는 크게 3가지로 나뉜다.

Channel의 종류로 channelExec, channelSftp, channelShell가 있는데
channelExec만으로 나머지를 커버할 수 있어서 이것만 사용합니다.

Setting

  1. pom.xml or gradle에서 Jsch(Java Secure Channel) depencency를 추가한다.
  <dependency>
      <groupId>com.jcraft</groupId>
      <artifactId>jsch</artifactId>
      <version>0.1.55</version>
  </dependency>
  compile group: 'com.jcraft', name: 'jsch', version: '0.1.55'
  1. Component를 생성한다.
@Component
public class SSHUtils {
    private final String username = {username};
    private final String host = {host};
    private final int port = {port};
    private final String password = {password};

    private Session session;
    private ChannelExec channelExec;
}

SSH 접속하기

    private void connectSSH() throws JSchException {
        session = new JSch().getSession(username, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");       // 호스트 정보를 검사하지 않도록 설정
        session.connect();
    }

Command 실행

    public void command(String command) {
        try {
            connectSSH();
            channelExec = (ChannelExec) session.openChannel("exec");	// 실행할 channel 생성

            channelExec.setCommand(command);	// 실행할 command 설정
            channelExec.connect();		// command 실행

        } catch (JSchException e) {
            logger.error("JSchException");
        } finally {
            this.disConnectSSH();
        }
    }

command 실행에 대한 결과값을 받고 싶으면 다음과 같이 코드를 수정하면 된다.

public String getSSHResponse(String sourceDirectory, String command) {
        try {
            connectSSH();
            channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(command);
            
            InputStream inputStream = channelExec.getInputStream();
            channelExec.connect();

            byte[] buffer = new byte[8192];
            int decodedLength;
            StringBuilder response = new StringBuilder();
            while ((decodedLength = inputStream.read(buffer, 0, buffer.length)) > 0)
                response.append(new String(buffer, 0, decodedLength));

            ...
            ...
            ...
            
        } catch (JSchException e) {
            logger.error("JSchException");
        } finally {
            this.disConnectSSH();
        }
        return response.toString();
    }

SSH 연결 해제

    private void disConnectSSH() {
        if (session != null) session.disconnect();
        if (channelExec != null) channelExec.disconnect();
    }
profile
오늘 달리면 내일 걸을 수 있다!

0개의 댓글