2014-11-21 60 views
1

我想使用ctypes API讀取Windows Credential Vault,但我不確定如何將函數結果轉回可用的ctypes.Structure。試圖使用ctypes調用wincred api

import ctypes 
class CREDENTIALS(ctypes.Structure): 
    _fields_ = [ 
     ("Flags", ctypes.c_int), 
     ("Type", ctypes.c_int), 
     ("TargetName", ctypes.c_wchar_p), 
     ("Comment", ctypes.c_wchar_p), 
     ("CredentialBlobSize", ctypes.c_int), 
     ("CredentialBlob", ctypes.c_wchar_p), 
     ("AttributeCount", ctypes.c_int), 
     ("Attributes", ctypes.c_wchar_p), 
     ("TargetAlias", ctypes.c_wchar_p), 
     ("UserName", ctypes.c_wchar_p) 
] 
advapi32 = ctypes.oledll.LoadLibrary('Advapi32.dll') 
advapi32.CredReadW.restype = ctypes.c_bool 
advapi32.CredReadW.argtypes = [ctypes.c_wchar_p, ctypes.c_int, ctypes.c_int, ctypes.POINTER(CREDENTIALS)] 
target = "login.example.com" 
pcred = ctypes.pointer(CREDENTIALS()) 
ok = advapi32.CredReadW(target,1,0,pcred) 
cred = pcred.contents 
print ok, pcred, cred.UserName, cred.CredentialBlob 

結果:

1 <__main__.LP_CREDENTIALS object at 0x012CECB0> None None

該函數返回true,所以它的工作原理,但指針內容似乎空白。我究竟做錯了什麼?

+0

因爲它看起來像你在x86上在你的CREDENTIALS類型幫助中添加'_pack_ = 1'嗎?從ctypes.wintypes '從ctypes的進口結構,指針,WinDLL' '進口LPWSTR,DWORD,BOOL,FILETIME,LPVOID': – Flexo 2014-11-22 11:05:59

回答

2

oledll應該是windlloledll用於返回HRESULT的功能。

CREDENTIAL的定義缺少一些字段(LastWrittenPersist)。定義(link)是:

typedef struct _CREDENTIAL { 
    DWORD     Flags; 
    DWORD     Type; 
    LPTSTR    TargetName; 
    LPTSTR    Comment; 
    FILETIME    LastWritten; 
    DWORD     CredentialBlobSize; 
    LPBYTE    CredentialBlob; 
    DWORD     Persist; 
    DWORD     AttributeCount; 
    PCREDENTIAL_ATTRIBUTE Attributes; 
    LPTSTR    TargetAlias; 
    LPTSTR    UserName; 
} CREDENTIAL, *PCREDENTIAL; 
+0

感謝您的幫助,我已經固定的結構定義使用WINDLL類型 – Stavr00 2014-11-24 15:45:15