2006/08/25

[C#]在程式中模擬特定的windows帳號存取網路芳鄰

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;

[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
[assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
namespace ConsoleApplication1
{
    class Class1
    {
        //登入
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(
           string lpszUsername,
           string lpszDomain,
           string lpszPassword,
           int dwLogonType,
           int dwLogonProvider,
           ref IntPtr phToken);
        //登出
        [DllImport("kernel32.dll")]
        public extern static bool CloseHandle(IntPtr hToken);

        public Class1()
        {
            string UserName = "username";
            string MachineName = "192.168.0.10";
            string Pw = "password";
            string IPath = @"\\" + MachineName + @"\shared";
            const int LOGON32_PROVIDER_DEFAULT = 0;
            const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
            IntPtr tokenHandle = new IntPtr(0);
            tokenHandle = IntPtr.Zero;
            //將登入的Token放在tokenHandle
            bool returnValue = LogonUser(UserName, MachineName, Pw,
            LOGON32_LOGON_NEW_CREDENTIALS,
            LOGON32_PROVIDER_DEFAULT,
            ref tokenHandle);

            //讓程式模擬登入的使用者
            WindowsIdentity w = new WindowsIdentity(tokenHandle);
            w.Impersonate();
            if (false == returnValue)
            {
                //登入失敗的處理
                return;
            }
            //取得該目錄下的所有檔案名稱
            DirectoryInfo dir = new DirectoryInfo(IPath);
            FileInfo[] inf = dir.GetFiles();
            for (int i = 0; i < inf.Length; i++)
            {
                Console.WriteLine(inf[i].Name);
            }
        }
    }
}
附註
  1. 如果電腦存在於網域, LogonUser的第二個參數須用網域名:
    LogonUser(UserName, "myDomain", Pw,LOGON32_LOGON_NEW_CREDENTIALS,
    LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
  2. 相關參考網頁: http://www.thecodeproject.com/csharp/cpimpersonation1.asp

沒有留言:

張貼留言