我正在尝试使用Python 3.7获取系统用户的登录时间。我已经尝试过用于Python的win32net和平台模块,但是函数没有在平台模块中定义,Win32net与Python 3和更多版本不兼容。我试过以下代码:
import platform
platform.uname()
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()
答案 0 :(得分:1)
尝试这些(首先安装win32com.client和子进程模块):
import win32com.client, time
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("SELECT * FROM Win32_NetworkLoginProfile")
def Convert_to_human_time(dtmDate):
strDateTime = ""
if dtmDate[4] == 0:
strDateTime = dtmDate[5] + '/'
else:
strDateTime = dtmDate[4] + dtmDate[5] + '/'
if dtmDate[6] == 0:
strDateTime = strDateTime + dtmDate[7] + '/'
else:
strDateTime = strDateTime + dtmDate[6] + dtmDate[7] + '/'
strDateTime = strDateTime + dtmDate[0] + dtmDate[1] + dtmDate[2] + dtmDate[3] + " " + dtmDate[8] + dtmDate[9] + ":" + dtmDate[10] + dtmDate[11] +':' + dtmDate[12] + dtmDate[13]
return strDateTime
for objItem in colItems:
if objItem.Name is not None:
print("Name: " + str(objItem.Name))
if objItem.LastLogon is not None:
print("Last Logon (Normal Format): " + str(objItem.LastLogon))
print("Last Logon (Human Readable Format): " + Convert_to_human_time(objItem.LastLogon))
if objItem.LastLogoff is not None:
print("Last Logoff (Normal Format): " + str(objItem.LastLogoff))
print("Last Logoff (Human Readable Format): " + Convert_to_human_time(objItem.LastLogoff))
if objItem.LogonHours is not None:
print("Logon Hours: " + str(objItem.LogonHours))
if objItem.LogonServer is not None:
print("Logon Server: " + str(objItem.LogonServer))
if objItem.NumberOfLogons is not None:
print("Number Of Logons: " + str(objItem.NumberOfLogons))
另一种方式:
from subprocess import check_output
import sys
get_result = check_output("wmic netlogin get name, fullname, lastlogon", shell=True, stderr=False)
print(get_result)
clean_result = str(get_result).lstrip("b'").rstrip("'").replace("\\r\\r\\n", "\n").replace('\n\n', '\n').split('\n')[2:-1]
for items in clean_result:
print(items.lstrip().rstrip())
祝你好运......