Java로 SSH로 접속하여 명령어를 실행하는 단계는 크게 3가지로 나뉜다.
Channel의 종류로 channelExec, channelSftp, channelShell가 있는데
channelExec만으로 나머지를 커버할 수 있어서 이것만 사용합니다.
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
compile group: 'com.jcraft', name: 'jsch', version: '0.1.55'
@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;
}
private void connectSSH() throws JSchException {
session = new JSch().getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no"); // 호스트 정보를 검사하지 않도록 설정
session.connect();
}
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();
}
private void disConnectSSH() {
if (session != null) session.disconnect();
if (channelExec != null) channelExec.disconnect();
}