JCC*_*CyC 13 .net c# registry credentials remote-access
如果我尝试在与我在同一域中的计算机中打开注册表(并且我的登录用户在目标计算机上具有管理员权限),则此.NET API可以正常工作.
如果它是一个具有不同的本地管理用户(我有密码)的域外机器,那就太棘手了.
我尝试在调用OpenRemoteBaseKey()之前使用WNetUseConnection()(过去在我想要读取远程磁盘文件的情况下很好用),但是没有骰子 - 我得到了访问被拒绝的异常.
显然,我必须以其他方式传递证书,但如何?
Osk*_*lin 33
我成功用于访问计算机上的文件的代码如下:
#region imports
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string
lpszUsername, string lpszDomain, string lpszPassword,
int dwLogonType, int dwLogonProvider, ref
IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto,
SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle
);
[DllImport("advapi32.dll", CharSet = CharSet.Auto,
SetLastError = true)]
public extern static bool DuplicateToken(IntPtr
existingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr
duplicateTokenHandle);
#endregion
#region logon consts
// logon types
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_LOGON_NETWORK = 3;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
// logon providers
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_PROVIDER_WINNT50 = 3;
const int LOGON32_PROVIDER_WINNT40 = 2;
const int LOGON32_PROVIDER_WINNT35 = 1;
#endregion
Run Code Online (Sandbox Code Playgroud)
然后签署部分,只需使用:
IntPtr token = IntPtr.Zero;
bool isSuccess = LogonUser("username", "domain", "password",
LOGON32_LOGON_NEW_CREDENTIALS,
LOGON32_PROVIDER_DEFAULT, ref token);
using (WindowsImpersonationContext person = new WindowsIdentity(token).Impersonate())
{
//do your thing
person.Undo();
}
Run Code Online (Sandbox Code Playgroud)
正如您可能看到的,"撤消()"将使您不再以该用户身份登录.所以在完成之前不要使用它.但别忘了使用它!
| 归档时间: |
|
| 查看次数: |
10692 次 |
| 最近记录: |