2 clases java LogsTools y SshTools que se pueden utilizar para conectarse a servidores en remoto con sesiones exec y ssh y obtener logs. Me ha sido muy útil para ver todos los logs a la vez de muchos servidores e instancias de una aplicación. Además se puede realizar un grep a partir de una cadena buscada y devuelve desde la primera linea del log donde aparece hasta la última, muy útil para buscar excepciones en logs muy grandes.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.rvillalba.utils.ssh.SshTools;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/**
* The Class LogsTools.
*/
public class LogsTools {
/** The Constant LOGGER. */
protected static final transient Logger LOGGER = Logger.getLogger(LogsTools.class);
/**
* Split log by filter.
*
* @param session
* the session
* @param logFilePath
* the log file path
* @param filter
* the filter
* @param numberLinesAfterLastOccurrence
* the number lines after last occurrence
* @return the list
*/
public static List<string> splitLogByFilter(Session session, String logFilePath, String filter,
Integer numberLinesAfterLastOccurrence) {
List<string> result = new ArrayList<string>();
try {
Integer firstLine = findFirstOccurrenceLine(session, logFilePath, filter);
Integer lastLine = findLastOccurrenceLine(session, logFilePath, filter);
if (firstLine != null && lastLine != null) {
result = split(session, logFilePath, numberLinesAfterLastOccurrence, firstLine, lastLine);
}
} catch (Exception e) {
LOGGER.error(e);
}
return result;
}
/**
* Split.
*
* @param session
* the session
* @param logFilePath
* the log file path
* @param numberLinesAfterLastOccurrence
* the number lines after last occurrence
* @param firstLine
* the first line
* @param lastLine
* the last line
* @return the list
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private static List<string> split(Session session, String logFilePath, Integer numberLinesAfterLastOccurrence,
Integer firstLine, Integer lastLine) throws IOException {
List<string> result = new ArrayList<string>();
String command = "cat " + logFilePath + " | head -" + ((lastLine) + numberLinesAfterLastOccurrence)
+ " | tail -" + ((lastLine - firstLine) + numberLinesAfterLastOccurrence + 1);
BufferedReader bufferedReader = SshTools.executeCommand(session, command);
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result.add(line);
}
return result;
}
/**
* Find last occurrence line.
*
* @param session
* the session
* @param logFilePath
* the log file path
* @param filter
* the filter
* @return the integer
* @throws Exception
* the exception
*/
private static Integer findLastOccurrenceLine(Session session, String logFilePath, String filter) throws Exception {
String command = "cat " + logFilePath + " | grep -n '" + filter + "' |tail -1 | cut -d : -f 1";
BufferedReader bufferedReader = SshTools.executeCommand(session, command);
String line = "";
Integer result = null;
while ((line = bufferedReader.readLine()) != null) {
result = Integer.valueOf(line);
}
return result;
}
/**
* Find first occurrence line.
*
* @param session
* the session
* @param logFilePath
* the log file path
* @param filter
* the filter
* @return the integer
* @throws Exception
* the exception
*/
private static Integer findFirstOccurrenceLine(Session session, String logFilePath, String filter) throws Exception {
String command = "cat " + logFilePath + " | grep -n '" + filter + "' |head -1 | cut -d : -f 1";
BufferedReader bufferedReader = SshTools.executeCommand(session, command);
String line = "";
Integer result = null;
while ((line = bufferedReader.readLine()) != null) {
result = Integer.valueOf(line);
}
return result;
}
/**
* Prints the logs line.
*
* @param bw
* the bw
* @param hostname
* the hostname
* @param fileName
* the file name
* @param logs
* the logs
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void printLogsLine(BufferedWriter bw, String hostname, String fileName, List<string> logs)
throws IOException {
if (logs != null && !logs.isEmpty()) {
bw.write("INICIO:" + hostname + ":" + fileName + ":");
bw.write("\r\n");
for (String line : logs) {
bw.write(hostname + ":" + fileName + ":" + line);
bw.write("\r\n");
}
}
}
/**
* Find in logs.
*
* @param bw
* the bw
* @throws JSchException
* the j sch exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void findInLogs(BufferedWriter bw, String hostnames, String paths, String login, String password,
String fileNames, String filter) throws JSchException, IOException {
for (String hostname : hostnames.split(";")) {
Session session = SshTools.remoteAccess(hostname, login, password, 22);
for (String path : paths.split(";")) {
for (String fileName : fileNames.split(";")) {
List<string> result = LogsTools.splitLogByFilter(session, path + fileName, filter, 15);
printLogsLine(bw, hostname, path + fileName, result);
}
}
SshTools.close(session);
}
bw.close();
}
}
package com.rvillalba.utils.ssh;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import org.apache.log4j.Logger;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/**
* The Class SshTools.
*/
public class SshTools {
/** The Constant LOGGER. */
protected static final transient Logger LOGGER = Logger.getLogger(SshTools.class);
/**
* Remote file access.
*
* @param host
* the host
* @param user
* the user
* @param pass
* the pass
* @param port
* the port
* @return the session
* @throws JSchException
* the j sch exception
*/
public static Session remoteAccess(String host, String user, String pass, Integer port) throws JSchException {
Session session = null;
try {
JSch jsch = new JSch();
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session = jsch.getSession(user, host, port);
session.setConfig(config);
session.setPassword(pass);
session.connect();
} catch (Exception e) {
LOGGER.error(e);
}
return session;
}
/**
* Generate channel.
*
* @param session
* the session
* @param command
* the command
* @return the channel
* @throws JSchException
* the j sch exception
*/
private static Channel generateChannel(Session session, String command) throws JSchException {
Channel channel = null;
try {
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
channel.connect();
} catch (Exception e) {
LOGGER.error(e);
}
return channel;
}
/**
* Generate shell channel.
*
* @param session
* the session
* @param commandToRun
* the command to run
* @return the channel
* @throws JSchException
* the j sch exception
*/
private static Channel generateShellChannel(Session session, String commandToRun) throws JSchException {
Channel channel = session.openChannel("shell");
OutputStream ops;
try {
ops = channel.getOutputStream();
channel.setOutputStream(System.out);
PrintStream ps = new PrintStream(ops, true);
channel.connect();
ps.println(commandToRun);
ps.println("exit");
ps.close();
do {
Thread.sleep(1000);
} while (!channel.isEOF());
} catch (Exception e) {
LOGGER.error(e);
}
return channel;
}
/**
* Execute shell command.
*
* @param session
* the session
* @param command
* the command
* @return the buffered reader
*/
public static BufferedReader executeShellCommand(Session session, String command) {
BufferedReader reader = null;
try {
Channel channel = generateShellChannel(session, command);
InputStream inputStream = channel.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
channel.disconnect();
} catch (Exception e) {
LOGGER.error(e);
}
return reader;
}
/**
* Execute command.
*
* @param session
* the session
* @param command
* the command
* @return the buffered reader
*/
public static BufferedReader executeCommand(Session session, String command) {
BufferedReader reader = null;
try {
Channel channel = generateChannel(session, command);
InputStream inputStream = channel.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
} catch (Exception e) {
LOGGER.error(e);
}
return reader;
}
/**
* Close.
*
* @param session
* the session
*/
public static void close(Session session) {
try {
session.disconnect();
} catch (Exception e) {
LOGGER.error(e);
}
}
}