Реализована команда uname

feature/add-uname-command
L_DelOff 2023-08-07 23:49:02 +03:00
parent fcd4929e0c
commit b6147e9e91
10 changed files with 211 additions and 62 deletions

View File

@ -1,5 +1,6 @@
package ru.ldeloff.servermonitorbot.controller; package ru.ldeloff.servermonitorbot.controller;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.bots.TelegramLongPollingBot;
@ -14,6 +15,7 @@ import ru.ldeloff.servermonitorbot.utils.ui.uname.UnameChatButtonAggregate;
@Service @Service
@Slf4j @Slf4j
@RequiredArgsConstructor
public class TelegramBotController extends TelegramLongPollingBot { public class TelegramBotController extends TelegramLongPollingBot {
final TelegramBot telegramBot; final TelegramBot telegramBot;
@ -22,14 +24,6 @@ public class TelegramBotController extends TelegramLongPollingBot {
final UnameChatButtonAggregate unameChatButtonAggregate; final UnameChatButtonAggregate unameChatButtonAggregate;
final TelegramBotService telegramBotService; final TelegramBotService telegramBotService;
public TelegramBotController(TelegramBot telegramBot, SshRepository sshRepository, TelegramBotKeyboard telegramBotKeyboard, UnameChatButtonAggregate unameChatButtonAggregate, TelegramBotService telegramBotService) {
this.telegramBot = telegramBot;
this.sshRepository = sshRepository;
this.telegramBotKeyboard = telegramBotKeyboard;
this.unameChatButtonAggregate = unameChatButtonAggregate;
this.telegramBotService = telegramBotService;
}
@Override @Override
public void onUpdateReceived(Update update) { public void onUpdateReceived(Update update) {
if (update.hasMessage()) { if (update.hasMessage()) {
@ -38,7 +32,7 @@ public class TelegramBotController extends TelegramLongPollingBot {
switch (messageText) { switch (messageText) {
case "/start" -> { case "/start" -> {
log.info("Получена команда /start"); log.info("Получена команда /start");
telegramBotService.switchToMainMenu(update, this); telegramBotService.firstUse(update, this);
} }
case "Статус" -> { case "Статус" -> {
log.info("Получена команда 'Статус'"); log.info("Получена команда 'Статус'");
@ -57,25 +51,20 @@ public class TelegramBotController extends TelegramLongPollingBot {
} else if (update.hasCallbackQuery()) { } else if (update.hasCallbackQuery()) {
String messageText = update.getCallbackQuery().getData(); String messageText = update.getCallbackQuery().getData();
String [] tags = messageText.split(":"); String [] tags = messageText.split(":");
switch (tags[0]) { if (tags.length > 1) {
case "uname": switch (tags[0]) {
if (tags.length > 1) { case "uname":
switch (tags[1]) { log.info("Получена команда '" + messageText + "'");
default -> { telegramBotService.uname(update, this);
log.warn("Неверный формат команды:" + messageText); break;
telegramBotService.switchToMainMenu(update, this); default:
break; log.warn("Неизвестная команда:" + messageText);
}
}
} else {
log.warn("Неверный формат команды:" + messageText);
telegramBotService.switchToMainMenu(update, this); telegramBotService.switchToMainMenu(update, this);
} break;
break; }
default : } else {
log.warn("Неизвестная команда:" + messageText); log.warn("Неверный формат команды:" + messageText);
telegramBotService.switchToMainMenu(update, this); telegramBotService.switchToMainMenu(update, this);
break;
} }
} }
} }

View File

@ -1,5 +0,0 @@
package ru.ldeloff.servermonitorbot.service;
public interface SshService {
}

View File

@ -1,8 +0,0 @@
package ru.ldeloff.servermonitorbot.service;
import org.springframework.stereotype.Service;
@Service
public class SshServiceImpl implements SshService {
}

View File

@ -8,4 +8,6 @@ public interface TelegramBotService {
void switchToMainMenu(Update update, TelegramBotController bot); void switchToMainMenu(Update update, TelegramBotController bot);
void getStatusSessions(Update update, TelegramBotController bot); void getStatusSessions(Update update, TelegramBotController bot);
void sendUnameAggregate(Update update, TelegramBotController bot); void sendUnameAggregate(Update update, TelegramBotController bot);
void uname(Update update, TelegramBotController bot);
void firstUse(Update update, TelegramBotController telegramBotController);
} }

View File

@ -1,5 +1,6 @@
package ru.ldeloff.servermonitorbot.service; package ru.ldeloff.servermonitorbot.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
@ -7,20 +8,28 @@ import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import ru.ldeloff.servermonitorbot.controller.TelegramBotController; import ru.ldeloff.servermonitorbot.controller.TelegramBotController;
import ru.ldeloff.servermonitorbot.repository.SshRepository; import ru.ldeloff.servermonitorbot.repository.SshRepository;
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
import ru.ldeloff.servermonitorbot.service.uname.UnameService;
import ru.ldeloff.servermonitorbot.utils.ui.TelegramBotKeyboard; import ru.ldeloff.servermonitorbot.utils.ui.TelegramBotKeyboard;
import ru.ldeloff.servermonitorbot.utils.ui.uname.UnameChatButtonAggregate; import ru.ldeloff.servermonitorbot.utils.ui.uname.UnameChatButtonAggregate;
@Slf4j @Slf4j
@Service @Service
@RequiredArgsConstructor
public class TelegramBotServiceImpl implements TelegramBotService { public class TelegramBotServiceImpl implements TelegramBotService {
final TelegramBotKeyboard telegramBotKeyboard; final TelegramBotKeyboard telegramBotKeyboard;
final SshRepository sshRepository;
final UnameChatButtonAggregate unameChatButtonAggregate; final UnameChatButtonAggregate unameChatButtonAggregate;
final UnameService unameService;
final SshService sshService;
public TelegramBotServiceImpl(TelegramBotKeyboard telegramBotKeyboard, SshRepository sshRepository, UnameChatButtonAggregate unameChatButtonAggregate) { @Override
this.telegramBotKeyboard = telegramBotKeyboard; public void firstUse(Update update, TelegramBotController bot) {
this.sshRepository = sshRepository; SendMessage message = new SendMessage();
this.unameChatButtonAggregate = unameChatButtonAggregate; long chatId = 0L;
chatId = update.getMessage().getChatId();
message.setText("Добро пожалвать " + update.getMessage().getChat().getUserName() + "!");
message.setChatId(chatId);
sendMessage(telegramBotKeyboard.uiForm(message), bot);
} }
@Override @Override
public void switchToMainMenu(Update update, TelegramBotController bot) { public void switchToMainMenu(Update update, TelegramBotController bot) {
@ -30,7 +39,6 @@ public class TelegramBotServiceImpl implements TelegramBotService {
chatId = update.getMessage().getChatId(); chatId = update.getMessage().getChatId();
} catch (Exception e) { } catch (Exception e) {
chatId = update.getCallbackQuery().getMessage().getChatId(); chatId = update.getCallbackQuery().getMessage().getChatId();
} }
message.setText("Неверная команда и или формат. Попробуем сначала."); message.setText("Неверная команда и или формат. Попробуем сначала.");
message.setChatId(chatId); message.setChatId(chatId);
@ -38,20 +46,18 @@ public class TelegramBotServiceImpl implements TelegramBotService {
} }
@Override @Override
public void getStatusSessions(Update update, TelegramBotController bot) { public void getStatusSessions(Update update, TelegramBotController bot) {
SendMessage message = new SendMessage(); sendMessage(sshService.getStatusSessions(update), bot);
long chatId = update.getMessage().getChatId();
message.setText(String.valueOf(sshRepository.getStatusSessions()));
message.setChatId(chatId);
sendMessage(message, bot);
} }
@Override @Override
public void sendUnameAggregate(Update update, TelegramBotController bot) { public void sendUnameAggregate(Update update, TelegramBotController bot) {
SendMessage message = new SendMessage(); sendMessage(unameService.sendUnameAggregate(update), bot);
long chatId = update.getMessage().getChatId();
message.setText(String.valueOf(sshRepository.getStatusSessions()));
message.setChatId(chatId);
sendMessage(unameChatButtonAggregate.uiForm(message), bot);
} }
@Override
public void uname(Update update, TelegramBotController bot) {
sendMessage(unameService.uname(update), bot);
}
private void sendMessage(SendMessage message, TelegramBotController bot) { private void sendMessage(SendMessage message, TelegramBotController bot) {
try { try {
bot.execute(message); bot.execute(message);

View File

@ -0,0 +1,16 @@
package ru.ldeloff.servermonitorbot.service.ssh;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import ru.ldeloff.servermonitorbot.model.SshServer;
import java.util.List;
public interface SshService {
SendMessage getStatusSessions(Update update);
List<SshServer> getSshServers();
String execute(String s, SshServer sshServer);
String execute(String s, SshServer sshServer, int timeout);
}

View File

@ -0,0 +1,66 @@
package ru.ldeloff.servermonitorbot.service.ssh;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import ru.ldeloff.servermonitorbot.model.SshServer;
import ru.ldeloff.servermonitorbot.repository.SshRepository;
import java.io.ByteArrayOutputStream;
import java.util.List;
@Service
@Slf4j
@RequiredArgsConstructor
public class SshServiceImpl implements SshService {
final SshRepository sshRepository;
@Override
public SendMessage getStatusSessions(Update update) {
SendMessage message = new SendMessage();
long chatId = update.getMessage().getChatId();
message.setText(sshRepository.getStatusSessions());
message.setChatId(chatId);
return message;
}
@Override
public List<SshServer> getSshServers() {
return sshRepository.getSshServers();
}
@Override
public String execute(String s, SshServer sshServer) {
return execute(s, sshServer, 100);
}
@Override
public String execute(String s, SshServer sshServer, int timeout) {
Session session = sshServer.getSession();
ChannelExec channel = null;
try {
channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(s);
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
channel.setOutputStream(responseStream);
channel.connect();
while (channel.isConnected()) {
Thread.sleep(timeout);
}
String responseString = new String(responseStream.toByteArray());
return responseString;
} catch (JSchException | InterruptedException e) {
log.error(e.getMessage());
return null;
} finally {
if (channel != null) {
channel.disconnect();
}
}
}
}

View File

@ -0,0 +1,10 @@
package ru.ldeloff.servermonitorbot.service.uname;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
public interface UnameService {
SendMessage sendUnameAggregate(Update update);
SendMessage uname(Update update);
}

View File

@ -0,0 +1,74 @@
package ru.ldeloff.servermonitorbot.service.uname;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import ru.ldeloff.servermonitorbot.model.SshServer;
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
import ru.ldeloff.servermonitorbot.utils.ui.uname.UnameChatButtonAggregate;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
@RequiredArgsConstructor
@Slf4j
public class UnameServiceImpl implements UnameService {
final SshService sshService;
final UnameChatButtonAggregate unameChatButtonAggregate;
@Override
public SendMessage sendUnameAggregate(Update update) {
SendMessage message = new SendMessage();
long chatId = update.getMessage().getChatId();
message.setChatId(chatId);
return unameChatButtonAggregate.uiForm(message);
}
@Override
public SendMessage uname(Update update) {
String messageText = update.getCallbackQuery().getData();
String [] tags = Arrays.stream(messageText.split(":"))
.map(String::trim)
.toArray(String[]::new);
String result;
if (tags[1].equals("all")) {
result = unameAllHost();
} else {
result = unameSpecificHost(tags[1]);
}
SendMessage message = new SendMessage();
long chatId = update.getCallbackQuery().getMessage().getChatId();
message.setChatId(chatId);
message.setText(result);
return message;
}
private String unameAllHost() {
List<SshServer> servers = sshService.getSshServers();
StringBuilder response = new StringBuilder();
servers.forEach(server -> {
response.append(unameSpecificHost(server.getName())).append("\n");
});
return response.toString();
}
private String unameSpecificHost(String serverName) {
Optional<SshServer> server = sshService.getSshServers()
.stream()
.filter(x -> x.getName().equals(serverName))
.findFirst();
if (server.isPresent()) {
String result = sshService.execute("uname -a", server.get());
return server.get().getName() + ": " + (Objects.isNull(result) ? "ошибка при выполнении команды" : result);
} else {
log.error("Ошибка при выполнении команды 'uname'. Искомый сервер (" + serverName + ") не найден");
return null;
}
}
}

View File

@ -1,25 +1,23 @@
package ru.ldeloff.servermonitorbot.utils.ui.uname; package ru.ldeloff.servermonitorbot.utils.ui.uname;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import ru.ldeloff.servermonitorbot.repository.SshRepository; import ru.ldeloff.servermonitorbot.repository.SshRepository;
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
import ru.ldeloff.servermonitorbot.utils.ui.UiFormer; import ru.ldeloff.servermonitorbot.utils.ui.UiFormer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@Component @Component
@RequiredArgsConstructor
public class UnameChatButtonAggregate implements UiFormer { public class UnameChatButtonAggregate implements UiFormer {
private final SshRepository sshRepository; private final SshService sshService;
@Autowired
public UnameChatButtonAggregate(SshRepository sshRepository) {
this.sshRepository = sshRepository;
}
@Override @Override
public SendMessage uiForm(SendMessage message) { public SendMessage uiForm(SendMessage message) {
@ -27,7 +25,7 @@ public class UnameChatButtonAggregate implements UiFormer {
InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup(); InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
sshRepository.getSshServers().forEach(sshServer -> { sshService.getSshServers().forEach(sshServer -> {
List<InlineKeyboardButton> keyboardRow = new ArrayList<>(); List<InlineKeyboardButton> keyboardRow = new ArrayList<>();
InlineKeyboardButton inlineKeyboardButton = new InlineKeyboardButton(); InlineKeyboardButton inlineKeyboardButton = new InlineKeyboardButton();
inlineKeyboardButton.setText(sshServer.getName()); inlineKeyboardButton.setText(sshServer.getName());
@ -44,6 +42,7 @@ public class UnameChatButtonAggregate implements UiFormer {
inlineKeyboardMarkup.setKeyboard(keyboard); inlineKeyboardMarkup.setKeyboard(keyboard);
message.setReplyMarkup(inlineKeyboardMarkup); message.setReplyMarkup(inlineKeyboardMarkup);
message.setText("Выполнить uname для");
return message; return message;
} }