2017-10-28 68 views
3

我想用Python 3.7獲取系統用戶的登錄時間。我已經嘗試過用於Python的win32net和平臺模塊,但是,函數沒有在平臺模塊中定義,而Win32net與Python 3和更多不兼容。我曾嘗試下面的代碼:Python 3.7:如何獲取Windows用戶登錄時間?

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() 
+3

Python 3.7仍處於alpha版本。你現在可能想要抱着你的馬並回到3.6。 –

+0

@MartijnPieters哈哈!是!我現在使用Django和Jupyter的Python 3.6。否則,在3.7上,我將始終在StackOverflow上而不是在Python上處於活動狀態。 –

回答

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()) 

好運...

+0

謝謝!第二個代碼運行完美。只是顯示格式稍微不對齊。我能夠得到我想要的! 謝謝! –

+0

@Himanshu_Singh_PM:你可以打我嗎? :) – DRPK

相關問題