[筆記]從別台Server抓檔案到loacal端(上)

  • 13513
  • 0

摘要:[筆記]從別台Server抓檔案到loacal端

一般電腦使用者在LAN裡常常用share folder分享一些檔案

在XP的網路芳鄰可以看到其他台電腦所分享的目錄

有權限就可以進入去瀏覽跟抓取

有連過就會記錄(有輸入帳號密碼的也是)

使用command line的"net use"就可以看到有連過那些電腦

重開機就或是delete就可以清掉。

但是當需要程式自動去抓檔回來處理的時候,

遇到需要輸入帳號密碼的時候該怎麼處理?

網路上有人分享四種方法:

C#访问远程主机资源的方法

1.下command line


        #region NET USE

        public bool Connect(string remoteHost, string userName, string passWord)
        {

            bool Flag = true;
            Process proc = new Process();
            proc.StartInfo.FileName = "cmd.exe";
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardInput = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.CreateNoWindow = true;

            try
            {

                proc.Start();
                string command = @"net  use  \\" + remoteHost + "  " + passWord + "  " + "  /user:" + userName + ">NUL";
                proc.StandardInput.WriteLine(command);
                command = "exit";
                proc.StandardInput.WriteLine(command);

                while (proc.HasExited == false)
                {
                    proc.WaitForExit(1000);
                }

                string errormsg = proc.StandardError.ReadToEnd();
                if (errormsg != "")
                    Flag = false;

                proc.StandardError.Close();
            }
            catch (Exception ex)
            {
                Flag = false;
                throw ex;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }

        public bool DisConnect(string remoteHost)
        {

            bool Flag = true;
            Process proc = new Process();
            proc.StartInfo.FileName = "cmd.exe";
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardInput = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.CreateNoWindow = true;

            try
            {

                proc.Start();
                string command = @"net  use  \\" + remoteHost + " /delete";
                proc.StandardInput.WriteLine(command);
                command = "exit";
                proc.StandardInput.WriteLine(command);

                while (proc.HasExited == false)
                {
                    proc.WaitForExit(1000);
                }

                string errormsg = proc.StandardError.ReadToEnd();
                if (errormsg != "")
                    Flag = false;

                proc.StandardError.Close();
            }
            catch (Exception ex)
            {
                Flag = false;
                throw ex;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }

        public bool FileCopy1(string filepath, string filename, string username, string password ,string desfilepath,string desfilename)
        {
            try
            {
                bool bln = false;

                bln = Connect(filepath, username, password);

                if (filename.Length > 0)
                {
                    File.Copy("\\\\" + filepath + "\\" + filename, desfilepath + "\\" + desfilename, true);
                }
                else
                {
                    DirectoryInfo source = new DirectoryInfo(filepath);
                    FileInfo[] finfo = source.GetFiles();

                    foreach (FileInfo f in finfo)
                    {
                        File.Copy(f.FullName, desfilepath + "\\" + desfilename, true);
                    }
                }

                bln = DisConnect(filepath);
                return bln;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

2.建立網路磁碟機


        #region 網路磁碟機

        [DllImport("mpr.dll", EntryPoint = "WNetAddConnection2")]
        public static extern uint WNetAddConnection2([In] NETRESOURCE lpNetResource, string lpPassword, string lpUsername, uint dwFlags);

        [DllImport("Mpr.dll")]
        public static extern uint WNetCancelConnection2(string lpName, uint dwFlags, bool fForce);

        [StructLayout(LayoutKind.Sequential)]
        public class NETRESOURCE
        {

            public int dwScope;
            public int dwType;
            public int dwDisplayType;
            public int dwUsage;
            public string LocalName;
            public string RemoteName;
            public string Comment;
            public string Provider;
        }

        // remoteNetworkPath format:  @"\\192.168.1.48\sharefolder"
        // localDriveName format:     @"O:"
        public static bool CreateMap(string userName, string password, string remoteNetworkPath, string localDriveName)
        {

            NETRESOURCE myNetResource = new NETRESOURCE();
            myNetResource.dwScope = 2;       //2:RESOURCE_GLOBALNET
            myNetResource.dwType = 1;        //1:RESOURCETYPE_ANY 
            myNetResource.dwDisplayType = 3; //3:RESOURCEDISPLAYTYPE_GENERIC
            myNetResource.dwUsage = 1;       //1: RESOURCEUSAGE_CONNECTABLE
            myNetResource.LocalName = localDriveName;
            myNetResource.RemoteName = remoteNetworkPath;
            myNetResource.Provider = null;

            uint nret = WNetAddConnection2(myNetResource, password, userName, 1);

            if (nret == 0)

                return true;

            else

                return false;

        }

        // localDriveName format:     @"O:"
        public static bool DeleteMap(string localDriveName)
        {

            uint nret = WNetCancelConnection2(localDriveName, 1, true);
            if (nret == 0)
                return true;
            else
                return false;

        }

        public bool FileCopy2(string filepath, string filename, string username, string password, string desfilepath, string desfilename)
        {
            try
            {
                bool bln = false;

                bln = CreateMap(username, password, @"\\" + filepath, @"O:");

                if (bln)
                {
                    File.Copy("O:\\" + filename, desfilepath + "\\" + desfilename,true);

                    bln = DeleteMap(@"O:");
                }

                return bln;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

3.利用WebClient

其實就像在IE上用檔案總管的功能,最終還是跟一般操作一樣


        #region WebClinet

        public bool FileCopy3(string filepath, string filename, string username, string password, string desfilepath, string desfilename)
        {
            try
            {
                bool bln = false;

                WebClient client = new WebClient();

                NetworkCredential cred = new NetworkCredential(username, password, filepath.Split('\\')[0]);

                client.Credentials = cred;

                client.DownloadFile("file://" + filepath + "/" + filename, desfilepath + "/" + desfilename);

                return bln;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

4.模擬角色


#region 角色模擬

        // 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;

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool RevertToSelf();

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);

        private WindowsImpersonationContext impersonationContext;

        public bool impersonateValidUser(String userName, String domain, String password)
        {

            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {

                // 這里使用LOGON32_LOGON_NEW_CREDENTIALS來訪問遠程資源。
                // 如果要(透過模擬用戶獲得權限)實現伺服器程序,訪問本地授權數據庫可
                // 以用LOGON32_LOGON_INTERACTIVE

                if (LogonUser(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS,
                LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {

                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {

                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();

                        if (impersonationContext != null)
                        {

                            System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                            IPrincipal pr = System.Threading.Thread.CurrentPrincipal;
                            IIdentity id = pr.Identity;
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }

            if (token != IntPtr.Zero)
                CloseHandle(token);

            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle(tokenDuplicate);

            return false;
        }

        public void undoImpersonation()
        {
            impersonationContext.Undo();
        }


        public bool FileCopy4(string filepath, string filename, string username, string password, string desfilepath, string desfilename)
        {
            try
            {
                bool bln = false;

                bln = impersonateValidUser(username, filepath.Split('\\')[0], password);

                if (bln)
                {
                    File.Copy("\\\\" + filepath + "\\" + filename, desfilepath + "\\" + desfilename, true);
                }


                if (bln) undoImpersonation();

                return bln;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion