Who Is Currently Connected: rapla-who.py

File rapla-who.py, 1.9 KB (added by kohlhaas, 4 years ago)
Line 
1#!/usr/bin/env python
2
3"""Search connected users.
4The standard input is the RAPLA server log file
5"""
6
7import sys
8
9class User:
10    def __init__(self, ip):
11        self.ip = ip
12        self.connect = 0
13        self.disconnect = 0
14        self.names = []
15
16    def __str__(self):
17        if self.connect != self.disconnect:
18            s = " ### Connected ###"
19        else:
20            s = ""
21        return ("%-15s %-37s (%2d,%2d)" % (self.ip, str(self.names),
22                                  self.connect, self.disconnect)) + s
23
24def date(line):
25    return line[6:20]
26
27class Logs:
28    def __init__(self, file):
29        logs = []
30
31        for line in file.readlines():
32            if line.endswith("Storage service started\n"):
33                self.start = date(line)
34                logs = []
35            else:
36                logs.append(line)
37
38        users = {}
39        last = None
40        self.stop = "Running"
41               
42        for log in logs:
43            if last:
44                name = log.split(" ")[-1][:-1]
45                if name not in last.names:
46                    last.names.append(name)
47                last.connect += 1
48                last = None
49                continue
50            if log.find("Client subscribed") >= 0:
51                ip = log.split(" /")[1].split(":")[0]
52                if not users.has_key(ip):
53                    users[ip] = User(ip)
54                last = users[ip]
55                continue
56            if log.find("Client unsubscribed") >= 0:
57                ip = log.split(" /")[1].split(":")[0]
58                users[ip].disconnect += 1
59                continue
60            if log.find("Storage service stopped") >= 0:
61                self.stop = date(line)
62
63        self.users = users
64
65    def __str__(self):
66        s = "Start date = %s, Stop date = %s\n" % (self.start, self.stop)
67        for u in self.users.values():
68            s += str(u) + "\n"
69        return s
70
71if __name__ == "__main__":
72    print Logs(sys.stdin)
73
74