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