-->

How to get the user login/logoff time by Python fo

2020-08-05 09:51发布

问题:

I am trying to develop a script or tool to tell about how long each user occupies the computer, in order to manage and balance the resource. As for the user name, Python provides clean way to get it by os.getlogin(). However, I searched and could not find a neat Python API method to get the login and logoff time of that specific user. For Windows, I have to "query user" and this does not work for windows XP. And for Linux, I have to admit I am not good at it. Do you guys know a cross-platform and Python API way to do that?.

Thanks a lot! Di

回答1:

Windows Solution (should work on xp)

>>> import win32net,time
>>> users,nusers,_ = win32net.NetUserEnum(None,2)
>>> for user in users:
...    print "%-20s %s"%(user['name'],time.ctime(user['last_logon']))
...
Administrator        Sat Oct 06 04:59:59 2012
Bob                  Mon Nov 05 10:03:17 2012
Guest                Wed Dec 31 16:00:00 1969
joran                Fri May 10 08:04:36 2013
SophosSAUNEREUS0     Fri May 10 13:31:26 2013
Umläut               Tue Nov 13 16:21:49 2012

you can use

import platform
platform.uname() 

to determine which OS you are in and use a separate method for each OS, for example

import platform
os_name = platform.uname()[0].lower()
if os_name == "windows":
   get_win_login_time()
elif os_name.endswith("nix"):
   get_nix_login_time()
....

to answer your question re network users

import win32net, win32netcon, platform

win32net.NetUserEnum(win32net.NetGetDCName(),2,win32netcon.FILTER_NORMAL_ACCOUNT)