我试图循环浏览一个日志(log)文本文件,其中包含SSH登录和其他日志(log).
程序正在返回SSH登录的总数.
我的解决方案确实有效,但似乎有点慢(在200mo文件中约3.5秒).我想知道是否有任何方法可以让它更快.我对Java的良好实践并不十分熟悉.
我用的是BufferedReader
级.也许有更好的课程/方法,但我在网上找到的其他东西都比较慢.
{
BufferedReader br;
if(fileLocation != null) {
br = new BufferedReader(new FileReader(fileLocation));
}
else {
br = new BufferedReader((new InputStreamReader(System.in, "UTF-8")));
}
String line;
Stack<String> users = new Stack<>();
int succeeded = 0;
int failed;
int total = 0;
if(!br.ready()) {
help("Cannot read the file", true);
}
while((line=br.readLine())!=null)
{
if(!line.contains("sshd")) continue;
String[] arr = line.split("\\s+");
if(arr.length < 11) continue;
String log = arr[4];
String log2 = arr[5];
String log3 = arr[8];
String user = arr[10];
if(!log.contains("sshd")) continue;
if(!log2.contains("Accepted")) {
if(log3.contains("failure")) {
total++;
}
continue;
}
total++;
succeeded++;
if(!repeat) {
if (users.contains(user)) continue;
users.add(user);
}
System.out.println((total + 1) + " " + user);
}
完整代码:https://pastebin.com/xp2P9wja
此外,以下是日志(log)文件的几行:
Dec 3 12:20:12 k332 sshd[25206]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=10.147.222.137
Dec 3 12:20:14 k332 sshd[25204]: error: PAM: Authentication failure for illegal user admin from 10.147.222.137
Dec 3 12:20:14 k332 sshd[25204]: Failed keyboard-interactive/pam for invalid user admin from 10.147.222.137 port 36417 ssh2
Dec 3 12:20:14 k332 sshd[25204]: Connection closed by invalid user admin 10.147.222.137 port 36417 [preauth]
Dec 3 12:20:40 k332 sshd[25209]: pam_tally2(sshd:auth): Tally overflowed for user root
最终输出为:
Total :
103 unique IP SSH logins succeeded
30387 SSH logins succeeded
17186 SSH logins failed
47573 total SSH logins
谢谢你抽出时间!
编辑:Mo(兆字节)=MB(兆字节)(我们通常在法语中说Mo)
以下是所有人都需要的完整更新代码:https://pastebin.com/Kn5EqLNX