一、挪用Net use敕令
// 运用要领: //if (Connect("192.168.1.48", "用户名", "暗码")) //{ // File.Copy(@"\\192.168.1.48\同享目次\test.txt", @"e:\\test.txt", true); //} 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; } finally { proc.Close(); proc.Dispose(); } return Flag; }
二、挪用WNetAddConnection2、WNetAddConnection3或许NetUseAdd函数,举行磁盘映照。
using System;using System.Collections.Generic;using System.Text; using System.Runtime.InteropServices; namespace WindowsApplication1{ public class MyMap { [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: @"E:" 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, 0); if (nret == 0) return true; else return false; } // localDriveName format: @"E:" public static bool DeleteMap(string localDriveName) { uint nret = WNetCancelConnection2(localDriveName, 1, true); if (nret == 0) return true; else return false; } public void test() { // 注重: // remote、local、username的花样一定要准确,不然能够涌现毛病 string remote = @"\\192.168.1.48\generals"; string local = @"P:"; string username = @"Domain\UserName"; string password = @"Password"; bool ret = MyMap.CreateMap(username, password, remote, local); if (ret) { //do what you want: // ... //File.Copy("q:\\test.htm", "c:\\test.htm"); MyMap.DeleteMap(local); } } }}
三、运用WebClient类
因为WebClient类能够上传下载文件,而且支撑以http:、https:和file:开首的URI,所以能够用WebClient类来传输文件。
增加System.Net定名空间后运用以下代码下载文件:
private void Test1() { try { WebClient client = new WebClient(); NetworkCredential cred = new NetworkCredential("username", "password", "172.16.0.222"); client.Credentials = cred; client.DownloadFile("file://172.16.0.222/test/111.txt", "111.txt"); } catch (Exception ex) { // 假如收集很慢,而文件又很大,这时候能够有超时非常(Time out)。 } } public void Test2() { try { WebClient client = new WebClient(); NetworkCredential cred = new NetworkCredential("username", "password", "domain"); client.Credentials = cred; client.DownloadFile("file://172.16.0.222/test/111.txt", "111.txt"); } catch (Exception ex) { // 假如收集很慢,而文件又很大,这时候能够有超时非常(Time out)。 } }
相似的还能够尝尝WebRequest、FileWebRequest等:
WebRequest req = WebRequest.Create("file://138.12.12.14/generals/test.htm"); NetworkCredential cred = new NetworkCredential("username", "password", "IP"); req.Credentials = cred; WebResponse response = req.GetResponse(); Stream strm = response.GetResponseStream(); StreamReader r = new StreamReader(strm); ... ...
四、角色模仿
/// <summary> /// 身份模仿完成长途资本接见 /// </summary> public class FileImpersonation { // 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; /// <summary> /// 身份模仿 /// </summary> /// <param name="userName">自力效劳器用IP,域环境就用域名</param> /// <param name="domain"></param> /// <param name="password"></param> /// <returns></returns> 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) { 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; } /// <summary> /// 作废模仿身份 /// </summary> public void undoImpersonation() { impersonationContext.Undo(); } /// <summary> /// /// </summary> /// <param name="domain">自力效劳器用IP,域环境就用域名</param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="act">须要实行的操纵</param> public void ImpersonateFunc(string username, string domain, string password, Action act) { bool isImpersonated = false; try { if (impersonateValidUser(username, domain, password)) { isImpersonated = true; //File.Copy(@"\\192.168.1.48\generals\now.htm", "c:\\now.htm", true); act(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (isImpersonated) undoImpersonation(); } } // } FileImpersonation imp = new FileImpersonation(); imp.ImpersonateFunc("Administrator", "192.168.0.125", "xxxx", () => { var source = new DirectoryInfo(@"D:\HR"); string targetFolder = @"\\192.168.0.125\d$\HR"; if (!Directory.Exists(targetFolder)) { Directory.CreateDirectory(targetFolder); } foreach (FileInfo item in source.GetFiles()) { string targertFile = Path.Combine(targetFolder, item.Name); File.Copy(item.FullName, targertFile, true); } });
五、比较
要领一经由过程挪用Shell敕令Net Use完成,有点愚笨。
要领二和要领一有些相似之处。映照长途资本,然后接见。
要领三因为会有超时非常涌现,所以在收集速度快、传输小文件时是能够的。
要领四经由过程身份模仿完成长途资本接见。一些效劳器历程就是经由过程这类体式格局运转的。这类要领也是我的最爱。
六、要注重的处所
关于这几种要领,google后都能够找到一些文章。然则比及本身现实测试时,有时会涌现种种小毛病,
这些毛病基础来源于两方面:
1、函数的参数挑选有题目,和本身的环境不符合。
比方
public static extern int LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
中的dwLogonType,要接见长途资本就要用LOGON32_LOGON_NEW_CREDENTIALS,
要模仿本机用户就要用LOGON32_LOGON_INTERACTIVE。
2、函数的参数花样有题目。
a、比方
public static extern int LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
中的lpszUserName、lpszDomain、lpszPassword就要写清晰。
我就在这遇到过题目,第一次测试时,长途效劳器就是一台自力的文件效劳器,这是我的挪用体式格局:
LogonUser("myname", "192.168.1.48", "password", LOGON32_LOGON_NEW_CREDENTIALS,
LOGON32_PROVIDER_DEFAULT, ref token);
第二次测试时,长途效劳器是域MyDomain中的一个成员效劳器,供应文件效劳。这时候代码就应该是:
LogonUser("myname", "MyDomain", "password", LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token);
注重,代码中是MyDomain而不是IP地点。
b、再如:
参考上面代码
string remote = @"\\192.168.1.48\generals"; string local = @"P:"; string username = @"Domain\UserName"; string password = @"Password";
假如@"\\192.168.1.48\generals"变成@"\\192.168.1.48\generals\”就会失足;
假如是域中的用户,那末把@"Domain\UserName"变成@"UserName"就会失足。
以上就是C#接见长途主机资本的多种要领分享的细致内容,更多请关注ki4网别的相干文章!