訓練家的快寫筆記

The legend of trainer's paper


搜尋:

     關閉     
標題:C# 抓網芳資料
內容:

C# 登入網路芳鄰讀取檔案
http://allenj.info/article/post/271
C# 指定帳號讀取網路磁碟機資料
https://docs.google.com/document/d/1YJNIYOoGat5bSKnpBtXRAUXwkDxRdnsU6w42FKqNeD8/edit?usp=sharing

 private void CopyFileToNetwork()
   {
       System.IO.StreamReader sErr;
       System.IO.StreamReader sOut;
       String tempErr, tempOut;
       System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
       myProcess.StartInfo.FileName = @"NET";
       myProcess.StartInfo.Arguments = "USE Y: \\\\192.168.0.136\\folder001 \"123456\" /user:\"Administrator\""; //password is 123456, username is Administrator
       myProcess.StartInfo.CreateNoWindow = true;
       myProcess.StartInfo.UseShellExecute = false;
       myProcess.StartInfo.RedirectStandardError = true;
       myProcess.StartInfo.RedirectStandardOutput = true; // 導出 StandardOutput
       try
       {
           myProcess.Start();
           myProcess.WaitForExit(10000);
 
           if (!myProcess.HasExited)
           {
               myProcess.Kill();
               Response.Write("執行失敗!!");
           }
           else
           {
               sErr = myProcess.StandardError;
               tempErr = sErr.ReadToEnd();
               sErr.Close();
 
               sOut = myProcess.StandardOutput;
               tempOut = sOut.ReadToEnd();
               sOut.Close();
 
               if (myProcess.ExitCode == 0) //連線磁碟機建立成功
               {
                   //Response.Write("執行成功" + "<BR>" + tempOut.ToString()); // 把執行結果也印出來
                   System.IO.File.Copy(@"D:\abc.xls", @"Y:\abc.xls",true);
               }
               else if (myProcess.ExitCode == 2) // 忽略連線磁碟機已存在
               {
                   System.IO.File.Copy(@"D:\abc.xls", @"Y:\abc.xls", true);
               }
               else
               {
                   Response.Write(tempErr);
               }
           }
       }
       catch (Exception ex)
       {
           Response.Write(ex.Message);
           myProcess.Close();
       }
       finally
       {
           myProcess.Close();
       }
   }



第二招


using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace FCUGIS.RD.MaintainHandler.lib
{
   public class IdentityImpersonation : IDisposable
    {
       [DllImport("advapi32.dll", SetLastError = true)]
       public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
       
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);


        public const int LOGON32_LOGON_NEW_CREDENTIALS = 9; //直接存取網路芳鄰

        public const int LOGON32_LOGON_INTERACTIVE = 2; //本地登錄


        // 要模擬的用戶的用戶名、密碼、域(機器名)

        private String _sImperUsername;

        private String _sImperPassword;

        private String _sImperDomain;

        // 記錄模擬上下文

        private WindowsImpersonationContext _imperContext;

        private IntPtr _adminToken;

        private IntPtr _dupeToken;

        // 是否已停止模擬

        private Boolean _bClosed;

        public Boolean IsLogined
        {
            get
            {
                return !_bClosed;
            }
        }


        /// 

        /// 構造函數

        /// 

        /// 所要模擬的用戶的用戶名

        /// 所要模擬的用戶的密碼

        /// 所要模擬的用戶所在的域

        public IdentityImpersonation(String impersonationUsername, String impersonationPassword, String impersonationDomain)
        {

            _sImperUsername = impersonationUsername;

            _sImperPassword = impersonationPassword;

            _sImperDomain = impersonationDomain;


            _adminToken = IntPtr.Zero;

            _dupeToken = IntPtr.Zero;

            _bClosed = true;

        }



        /// 

        /// 析構函數

        /// 

        ~IdentityImpersonation()
        {

            if (!_bClosed)
            {

                StopImpersonate();

            }

        }

        


        /// 

        /// 開始身份角色模擬。

        /// 

        /// 

        public Boolean BeginImpersonate()
        {

            Boolean bLogined = LogonUser(_sImperUsername, _sImperDomain, _sImperPassword, LOGON32_LOGON_INTERACTIVE, 0, ref _adminToken);



            if (!bLogined)
            {

                return false;

            }


            Boolean bDuped = DuplicateToken(_adminToken, 2, ref _dupeToken);



            if (!bDuped)
            {

                return false;

            }


            WindowsIdentity fakeId = new WindowsIdentity(_dupeToken);

            _imperContext = fakeId.Impersonate();



            _bClosed = false;



            return true;

        }



        /// 

        /// 停止身份角色模擬。

        /// 

        public void StopImpersonate()
        {

            _imperContext.Undo();

            CloseHandle(_dupeToken);

            CloseHandle(_adminToken);

            _bClosed = true;

        }

        void IDisposable.Dispose()
        {
            StopImpersonate();
        }
    }
}


第三招

protected void Page_Load(object sender, EventArgs e)
{
    string MachineName = "192.168.xxx.xxx";
    string UserName = "xxxx";
    string Pw = "xxxx";
    string IPath = String.Format(@"\\{0}\abc", MachineName);
    const int LOGON32_PROVIDER_DEFAULT = 0;
    const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
    IntPtr tokenHandle = new IntPtr(0);
    tokenHandle = IntPtr.Zero;
 
    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++)
    {
        Response.Write(inf[i].Name + "<br>");
    }
}
 
//登入
[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);