78 lines
3.4 KiB
Java
78 lines
3.4 KiB
Java
package com.ruoyi.cai.util;
|
||
|
||
import com.ruoyi.common.exception.base.BaseException;
|
||
import lombok.extern.slf4j.Slf4j;
|
||
import org.apache.commons.exec.*;
|
||
import org.apache.commons.exec.environment.EnvironmentUtils;
|
||
|
||
import java.io.ByteArrayOutputStream;
|
||
import java.io.IOException;
|
||
import java.nio.charset.StandardCharsets;
|
||
import java.util.Arrays;
|
||
import java.util.Collections;
|
||
import java.util.List;
|
||
import java.util.Map;
|
||
import java.util.stream.Collectors;
|
||
|
||
@Slf4j
|
||
public class LoginLogByFileUtil {
|
||
|
||
public static List<String> getLog(String mobile){
|
||
// 1. 定义命令(带管道的Linux命令,需用/bin/sh -c包裹)
|
||
String commandFormat = "tac /home/server/api/logs/sys-console.log | grep \"%s\" | grep -m 10 \"auth/login\"";
|
||
String command = String.format(commandFormat, mobile);
|
||
CommandLine cmdLine = CommandLine.parse("/bin/sh -c " + command); // 自动处理参数分隔
|
||
|
||
// 2. 配置执行器(设置超时、流处理)
|
||
DefaultExecutor executor = new DefaultExecutor();
|
||
executor.setExitValue(0); // 期望的退出码(0表示成功)
|
||
|
||
// 设置进程超时(5秒,适配你的快速执行场景)
|
||
ExecuteWatchdog watchdog = new ExecuteWatchdog(5000); // 5000ms = 5s
|
||
executor.setWatchdog(watchdog);
|
||
|
||
// 3. 处理输出(ByteArrayOutputStream存储10行结果,或用PumpStreamHandler实时处理)
|
||
// 场景1:存储结果到内存(仅10行,内存无压力)
|
||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, outputStream); // 合并标准输出/错误流
|
||
executor.setStreamHandler(streamHandler);
|
||
|
||
// 场景2:实时处理每行输出(推荐,避免存储)
|
||
// PumpStreamHandler streamHandler = new PumpStreamHandler(new LogOutputStream() {
|
||
// @Override
|
||
// protected void processLine(String line, int level) {
|
||
// // 实时处理每行数据(如输出到前端、写入日志)
|
||
// System.out.println(line);
|
||
// }
|
||
// });
|
||
// executor.setStreamHandler(streamHandler);
|
||
|
||
try {
|
||
// 4. 执行命令(环境变量使用系统默认,可自定义)
|
||
Map<String, String> env = EnvironmentUtils.getProcEnvironment();
|
||
executor.execute(cmdLine, env);
|
||
|
||
// 5. 解析结果(场景1的方式)
|
||
String result = outputStream.toString(StandardCharsets.UTF_8.name());
|
||
String[] split = result.split(System.lineSeparator());
|
||
List<String> lines = Arrays.stream(split).collect(Collectors.toList());
|
||
System.out.println("匹配的行数:" + lines.size());
|
||
lines.forEach(System.out::println);
|
||
|
||
} catch (ExecuteException e) {
|
||
if (watchdog.killedProcess()) {
|
||
log.error("命令执行超时,已终止进程");
|
||
} else {
|
||
log.error("命令执行失败,退出码:" + e.getExitValue());
|
||
}
|
||
log.error(e.getMessage(),e);
|
||
throw new BaseException("命令执行失败");
|
||
} catch (IOException e) {
|
||
log.error("IO异常:" + e.getMessage());
|
||
log.error(e.getMessage(),e);
|
||
throw new BaseException("IO异常");
|
||
}
|
||
return Collections.emptyList();
|
||
}
|
||
}
|