Format SSH login log entries

This commit is contained in:
2026-02-08 01:58:40 +03:00
parent dbf9b1fd2f
commit c8db1be2d8

View File

@@ -69,7 +69,7 @@ async def ssh_log(msg: Message):
await msg.answer("⏳ Loading SSH logins…", reply_markup=system_logs_kb)
async def worker():
lines: list[str] = []
raw_lines: list[str] = []
rc, out = await run_cmd(
[
"journalctl",
@@ -86,26 +86,50 @@ async def ssh_log(msg: Message):
if rc == 0 and out.strip():
for line in out.splitlines():
if "Accepted" in line:
lines.append(line)
raw_lines.append(line)
if not lines:
if not raw_lines:
rc2, out2 = await run_cmd(["tail", "-n", "200", "/var/log/auth.log"], timeout=10)
if rc2 == 0 and out2.strip():
for line in out2.splitlines():
if "Accepted" in line:
lines.append(line)
raw_lines.append(line)
if not lines:
if not raw_lines:
await msg.answer("🔑 SSH log\n\n(no logins today)", reply_markup=system_logs_kb)
return
recent = lines[-30:]
text = "🔑 SSH logins (today)\n```\n" + "\n".join(recent) + "\n```"
recent = raw_lines[-30:]
pretty = [_format_ssh_line(line) for line in recent]
text = "🔑 SSH logins (today)\n```\n" + "\n".join(pretty) + "\n```"
await msg.answer(text, reply_markup=system_logs_kb, parse_mode="Markdown")
asyncio.create_task(worker())
def _format_ssh_line(line: str) -> str:
parts = line.split()
if len(parts) < 10:
return line
month, day, time_str = parts[0], parts[1], parts[2]
user = "?"
ip = "?"
key_type = "?"
if "for" in parts:
i = parts.index("for")
if i + 1 < len(parts):
user = parts[i + 1]
if "from" in parts:
i = parts.index("from")
if i + 1 < len(parts):
ip = parts[i + 1]
if "ssh2:" in parts:
i = parts.index("ssh2:")
if i + 1 < len(parts):
key_type = parts[i + 1]
return f"{month} {day} {time_str} {user} @ {ip} ({key_type})"
@dp.message(F.text == "📈 Metrics")
async def metrics(msg: Message):
if not is_admin_msg(msg):