我在网上寻找一种方法来模拟我的 python 代码作为我的管理员帐户。 有很多共同的建议,但都缺少完整的过程,所以想分享一下。
我们需要先注册 win32 dll,然后才能与 windows api 通信。
在CMD.exe中“pip install pywin32”
安装成功后,我们需要在 sciprts 文件夹下运行“python Scripts/pywin32_postinstall.py -install”。 这将为 win32 api 注册所有模块/dll
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”学到的:)
如果我在本地网络上并且想在另一台设备上模拟 Windows 本地用户,应该用什么来代替“域”?