File: finger.py

package info (click to toggle)
python-utmp 0.8%2Bnmu1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, squeeze, wheezy
  • size: 192 kB
  • ctags: 194
  • sloc: python: 796; ansic: 583; makefile: 41; sh: 2
file content (193 lines) | stat: -rwxr-xr-x 5,323 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/python

import utmp
from UTMPCONST import *
import time, pwd, grp, os, string, sys, socket, popen2
from stat import *
from string import lower


def getrealname(gec):
    # get real name from gecos fiels
    return string.split(gec,",",1)[0]

def formatidle(t):
    if t<30:
        return ""
    if t<80:
        r = "%ss" % int(t)
        return r
    if t<60*80:
        return "%sm" % int(t/60)
    if t<60*60*28:
        return "%sh" % int(t/60/60)
    if t<60*60*24*20:
        return "%sd" % int(t/60/60/24)
    return "DEAD"

def userlist(u, now, user=""):
    u.setutent()
    tnow = time.mktime(now)
    header = 0
    output = [] # list of output lines, without header
    while 1:
        b = u.getutent()
        if not b:
            break
        if b.ut_type == USER_PROCESS:
            username = b.ut_user
            if user and b.ut_user!=user:
                continue
            try:
                pwnam = pwd.getpwnam(username)
            except KeyError:
                pwnam = '?'

            tty = b.ut_line

            t = time.localtime(b.ut_tv[0])
            then = time.mktime(t)
            if tnow<then: # login in the future?
                login = "FUTURE"
            elif t[7] == now[7] and t[0] == now[0]: # today
                login = time.strftime("%H:%M", t)
            elif tnow-then<60*60*24*7: # this week
                login = time.strftime("%a", t)
            elif tnow-then<60*60*24*365.: # this year
                login = time.strftime("%d-%b", t)
            else: # way down in the past
                login = time.strftime("%Y", t)
            location = b.ut_host
            tty = b.ut_line
            try:
                s = os.stat("/dev/"+tty)
                p = s[ST_MODE] & 0x30 # 060 octal - test executable bit
                if tnow<s[ST_ATIME]:
                    idle = 0
                else:
                    idle = tnow-s[ST_ATIME]
                idle = formatidle(idle)
                if p:
                    p = ' '
                else:
                    p = '*'
            except:
                p = '?'
                
            if p == '?':
                continue
            #length sanitation
            username = username[:12]
            #realname = realname[:22]
            login = login[:6]
            location = location[:30]

            if not header:
                #print 60*"-"
                print ("%-12s%-7s%-4s%-2s%-8s%-30s" % \
                       ("USERNAME","Login","Idle","", "TTY","Location")
                      )
                #print 60*"-"
                header = 1
        
            output.append( "%-12s%-7s%4s%2s%-8s%-30s" % 
                   (username,login,idle,p,tty,location) )
    output.sort()
    for i in output:
        print(i)
    return output

def lastlogin(u, user):
    lastlogin = 0, ""
    u.setutent()
    while 1:
        b = u.getutent_dict()
        if not b:
            break
        if b.ut_type in (USER_PROCESS, DEAD_PROCESS) and \
           b.ut_user == user and \
           b.ut_tv[0]>lastlogin[0]:
            lastlogin = b.ut_tv[0], b.ut_host

    u = utmp.UtmpRecord(WTMP_FILE)
    while 1:
        b = u.getutent_dict()
        if not b:
            break
        if b.ut_type in (USER_PROCESS, DEAD_PROCESS) and \
           b.ut_user == user and \
           b.ut_tv[0]>lastlogin[0]:
            lastlogin = b.ut_tv[0], b.ut_host
    u.endutent()
    return lastlogin

def userplan(homedir):          
    try:
        f = open(homedir+"/.plan", "r")
        print("Plan:")
        while 1:
            l = f.readline()
            if not l:
                break
            print string.rstrip(l)
    except:
        pass


def oneuser(u, user):
    pwent = pwd.getpwnam(user)
    rn = getrealname(pwent[4])
    print ("Login name: %-30s In real life: %s" % (user, rn))
    print (" Directory: %-30s Shell: %s" % (pwent[5], pwent[6]))
    print ("            %-30s Group: [%s]" % ("", grp.getgrgid(pwent[3])[0]))
    l, h = lastlogin(u, user)
    if not l:
        print("Never logged in.")
    else:
        r = "Last login %-30s  " % time.strftime("%A, %d-%b-%Y %H:%M", time.localtime(l))
        if h:
            r = r+'from: '+h
        print(r)
    print('\n')
    userplan(pwent[5])

print('\n')

if len(sys.argv) == 2 and "@" in sys.argv[1]: # remote
    user, host = string.split(sys.argv[1], "@", 1)
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        FINGER_PORT = 79
        s.connect( (host, FINGER_PORT) )
        s.send(user + '\r\n')
        while 1:
            buf = s.recv(1024)
            if not buf: break
            sys.stdout.write(buf)
        sys.stdout.flush()
    except socket.error, why:
        print "ERROR:", why
    sys.exit(0)

now = time.localtime(time.time())
a = utmp.UtmpRecord()

if len(sys.argv) == 1: # list of all local users
    r = userlist(a, now)
    if not r:
        print "No such processes."

else:
    #first find out if user exists
    user = sys.argv[1]
    try:
        pwd.getpwnam(user)
        r = userlist(a, now, user)
        if not r:
            print '"%s" isn\'t logged in.' % user
        print
        oneuser(a, user)
    except KeyError:
        print '"%s" does not match any user of this system.' % user
a.endutent()