WtmpFile && follow_main
authorTero Marttila <terom@paivola.fi>
Fri, 21 Mar 2008 02:02:52 +0200
changeset 8 3d648daf9538
parent 7 6a49fc285842
child 9 75cc996c6ba1
WtmpFile && follow_main

committer: Tero Marttila <terom@paivola.fi>
utmp.py
--- a/utmp.py	Fri Mar 21 01:53:51 2008 +0200
+++ b/utmp.py	Fri Mar 21 02:02:52 2008 +0200
@@ -1,4 +1,4 @@
-import socket
+import socket, os, time
 
 import _utmp
 
@@ -7,28 +7,38 @@
         "type", "pid", "line", "id", "user", "host", "exit", "session", "tv", "addr_v6"
     )
 
+    @staticmethod
+    def fromFile (file) :
+        bytes = file.read(_utmp.size())
+
+        if not bytes :
+            return
+
+        result = _utmp.parse(bytes)
+        
+        wtmp = WtmpEntry()
+
+        for name, field in zip(wtmp._ATTRS, result) :
+            if isinstance(field, str) and name not in ("addr_v6", ) :
+                field = field.rstrip("\0")
+
+            setattr(wtmp, name, field)
+        
+        wtmp.addr_v6 = socket.inet_ntop(socket.AF_INET6, wtmp.addr_v6)
+
+        return wtmp
+
     def __str__ (self) :
         return " ".join("%s=%s" % (key, getattr(self, key)) for key in self._ATTRS)
 
-def read_entry (file) :
-    bytes = file.read(_utmp.size())
-
-    if not bytes :
-        return
+class WtmpFile (object) :
+    def __init__ (self, path="/var/log/wtmp") :
+        self.path = path
+        self.file = open(path)
+        self.file.seek(0, os.SEEK_END)
 
-    result = _utmp.parse(bytes)
-    
-    wtmp = WtmpEntry()
-
-    for name, field in zip(wtmp._ATTRS, result) :
-        if isinstance(field, str) and name not in ("addr_v6", ) :
-            field = field.rstrip("\0")
-
-        setattr(wtmp, name, field)
-    
-    wtmp.addr_v6 = socket.inet_ntop(socket.AF_INET6, wtmp.addr_v6)
-
-    return wtmp
+    def tryRead (self) :
+        return WtmpEntry.fromFile(self.file)
 
 def read_entries (file) :
     while True :
@@ -39,6 +49,17 @@
         else :
             return
 
+def follow_main () :
+    wtmp = WtmpFile()
+    
+    while True :
+        item = wtmp.tryRead()
+
+        if item :
+            print item
+        else :
+            time.sleep(2)
+
 def test_main () :
     fh = open("/var/log/wtmp", "r")
     
@@ -46,5 +67,5 @@
         print item
 
 if __name__ == '__main__' :
-    test_main()
+    follow_main()