在Python窗口中成功模拟为用户的步骤

2024-05-15 04:43:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在网上搜寻,想找到一种方法,把我的python代码模拟成我的管理员帐户。 有很多共同的建议,但都错过了完整的过程,所以想分享一下

We need win32 dlls registered before we can communicate with windows api.

在CMD.exe中“pip安装pywin32”

After successful install we need to run "python Scripts/pywin32_postinstall.py -install" under sciprts folder. This will register all modules/dll for win32 api


import win32security, win32con, win32.win32api , win32 ,win32.win32security

class Impersonate:
    def __init__(self, login, password):
        self.domain = 'domain'
        self.login = login
        self.password = password

    def logon(self):
        self.handle = win32.win32security.LogonUser(self.login, self.domain,self.password,win32con.LOGON32_LOGON_INTERACTIVE,win32con.LOGON32_PROVIDER_DEFAULT)
        win32.win32security.ImpersonateLoggedOnUser(self.handle)

    def logoff(self):
        win32security.RevertToSelf() # terminates impersonation
        self.handle.Close() # guarantees cleanup

if __name__=='__main__':
    a = Impersonate('user_name','user_password')

    # Logging in
    a.logon()

    # Do whatever
    print(f"\n\t\tImprosonating: {win32.win32api.GetUserName()}")

    #Another way to call an Object
    Impersonate.logoff(a) # Logoff and Clean up

参考: https://pypi.org/project/pywin32/

谢谢:哈蒙德

*不是我的代码,从“Python Cookbook”中学到:


Tags: 代码selfapidomaindefloginpasswordneed

热门问题