如何在c#程序中模拟域帐户进行登录操作

代码加注释:

01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Text;
05using System.Security.Principal;
06using System.Runtime.InteropServices;
07using System.IO;
08  
09namespace ConsoleApplication3
10{
11    internal static class WinLogonHelper
12    {
13        /// <summary>
14        /// 模拟windows登录域
15        /// http://www.cnblogs.com/yukaizhao/
16        /// </summary>
17        [DllImport("advapi32.DLL", SetLastError = true)]
18        public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
19    }
20  
21    class Program
22    {
23        static void Main(string[] args)
24        {
25            IntPtr admin_token = default(IntPtr);
26            WindowsIdentity wid_admin = null;
27            WindowsImpersonationContext wic = null;
28  
29            //在程序中模拟域帐户登录
30            if (WinLogonHelper.LogonUser("uid", "serverdomain", "pwd", 9, 0, ref admin_token) != 0)
31            {
32                using (wid_admin = new WindowsIdentity(admin_token))
33                {
34                    using (wic = wid_admin.Impersonate())
35                    {
36                        //假定要操作的文件路径是10.0.250.11上的d:/txt.txt文件可以这样操作
37                        FileInfo file = new FileInfo(@"//10.0.250.11/d$/txt.txt");
38                        //想做什么操作就可以做了
39                    }
40                }
41            }
42        }
43    }
44}

模拟域帐户之后,就有了模拟用户的权限,这里千万要注意安全!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值