C#实验将计算机加入域
来源:互联网 发布:vc网络编程实例 编辑:程序博客网 时间:2024/05/22 09:52
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Diagnostics;using System.DirectoryServices;using System.Drawing;using System.Linq;using System.Management;using System.Runtime.InteropServices;using System.Security.Principal;using System.Text;using System.Windows.Forms;namespace 加入域{ public partial class Form1 : Form { bool joinSuccess = false; string userName = ""; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //string domian = "Administrator"; string domain = "ecjtucs"; WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); Debug.Assert(currentIdentity != null, "currentIdentity != null"); WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity); //string domain = Environment.UserDomainName.ToString(); userName = Environment.MachineName.ToString(); EnumComputers(); //isInDomain("WORKGROUP","Schema"); //GetDomainName(); //userName = "LiuJun@ecjtucs.com"; if (currentPrincipal.IsInRole(domain)) { //MessageBox.Show(Environment.UserDomainName.ToString()); MessageBox.Show("该用户" + userName + "在域" + domain + "中"); } else MessageBox.Show("该用户" + currentPrincipal.Identity.Name + "不在域" + domain + "中"); } /// <summary> /// 判断客户机是否在域中,注意过滤Schema /// </summary> /// <param name="domainName"></param> /// <param name="hostName"></param> public void isInDomain(string domainName, string hostName) { bool isInTheDomain = false; using (DirectoryEntry root = new DirectoryEntry("WinNT:")) { foreach (DirectoryEntry domain in root.Children) { if (domain.Name.Equals(domainName)) { foreach (DirectoryEntry computer in domain.Children) { if (computer.Name.Equals(hostName)) { isInTheDomain = true; MessageBox.Show("在域中"); } } if (isInTheDomain == false) MessageBox.Show("不在域中"); } } } } /// <summary> /// 获取局域网中的域的名称和客户机的名称 /// </summary> private void EnumComputers() { TreeNode treeNode = new TreeNode("局域网"); this.treeView1.Nodes.Add(treeNode); using (DirectoryEntry root = new DirectoryEntry("WinNT:")) { foreach (DirectoryEntry domain in root.Children) { TreeNode node = new TreeNode(domain.Name); treeNode.Nodes.Add(node); foreach (DirectoryEntry computer in domain.Children) { TreeNode node_ = new TreeNode(computer.Name); node.Nodes.Add(node_); } } } } //获取域名 private static string GetDomainName() { // 注意:这段代码需要在Windows XP及较新版本的操作系统中才能正常运行。 SelectQuery query = new SelectQuery("Win32_ComputerSystem"); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) { foreach (ManagementObject mo in searcher.Get()) { if ((bool)mo["partofdomain"]) return mo["domain"].ToString(); } } return null; } public string SetDomainMembership(string DomainName, string UserName, string Password, out string err) { err = "successful"; // Invoke WMI to join the domain using (ManagementObject wmiObject = new ManagementObject(new ManagementPath("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'"))) { try { // Obtain in-parameters for the method ManagementBaseObject inParams = wmiObject.GetMethodParameters("JoinDomainOrWorkgroup"); inParams["Name"] = DomainName; inParams["Password"] = Password; inParams["UserName"] = UserName + "@" + DomainName; inParams["AccountOU"] = null; inParams["FJoinOptions"] = 3; // // Execute the method and obtain the return values. ManagementBaseObject outParams = wmiObject.InvokeMethod("JoinDomainOrWorkgroup", inParams, null); switch (outParams["ReturnValue"].ToString()) { case "5": err = "Access is denied"; break; case "87": err = "The parameter is incorrect"; break; case "110": err = "The system cannot open the specified object"; break; case "1323": err = "Unable to update the password"; break; case "1326": err = "Logon failure: unknown username or bad password"; break; case "1355": err = "The specified domain either does not exist or could not be contacted"; break; case "2224": err = "The account already exists"; break; case "2691": err = "The machine is already joined to the domain"; break; case "2692": err = "The machine is not currently joined to a domain"; break; } if (err.Equals("successful")) joinSuccess = true; else joinSuccess = false; return err; } catch (ManagementException e) { throw new Exception(e.Message); } } } /// <summary> /// 设置客户机的DNS /// </summary> /// <param name="domainDNS"></param> public static void SetDNS(string[] domainDNS) { //获取本机的IP地址和网关 ManagementObjectCollection moc = GetLocalIPAndGateway(); ManagementBaseObject inPar = null; ManagementBaseObject outPar = null; foreach (ManagementObject mo in moc) { //如果没有启用IP设置的网络设备则跳过 if (!(bool)mo["IPEnabled"]) { continue; } if (domainDNS != null) { //设置DNS inPar = mo.GetMethodParameters("SetDNSServerSearchOrder"); // 1.DNS 2.备用DNS inPar["DNSServerSearchOrder"] = domainDNS; outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null); } } } public static ManagementObjectCollection GetLocalIPAndGateway() { ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = wmi.GetInstances(); return moc; } public static int SetDomainMembership2(string DomainName, string UserName, string Password, out string err) { err = string.Empty; try { string DomainNameHost = DomainName; uint value1 = NetJoinDomain(null, DomainNameHost, null, UserName + "@" + DomainName, Password, (JoinOptions.NETSETUP_JOIN_DOMAIN | JoinOptions.NETSETUP_DOMAIN_JOIN_IF_JOINED | JoinOptions.NETSETUP_ACCT_CREATE)); err = value1.ToString(); return Convert.ToInt32(value1); } catch (Exception e) { err = e.ToString(); return -1; } } [DllImport("netapi32.dll", CharSet = CharSet.Unicode)] static extern uint NetJoinDomain( string lpServer, string lpDomain, string lpAccountOU, string lpAccount, string lpPassword, JoinOptions NameType); [Flags] enum JoinOptions { NETSETUP_JOIN_DOMAIN = 0x00000001, NETSETUP_ACCT_CREATE = 0x00000002, NETSETUP_ACCT_DELETE = 0x00000004, NETSETUP_WIN9X_UPGRADE = 0x00000010, NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x00000020, NETSETUP_JOIN_UNSECURE = 0x00000040, NETSETUP_MACHINE_PWD_PASSED = 0x00000080, NETSETUP_DEFER_SPN_SET = 0x10000000 } /// <summary> /// 启用DHCP服务器 /// </summary> public static void EnableDHCP() { ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = wmi.GetInstances(); foreach (ManagementObject mo in moc) { //如果没有启用IP设置的网络设备则跳过 if (!(bool)mo["IPEnabled"]) continue; //重置DNS为空 mo.InvokeMethod("SetDNSServerSearchOrder", null); //开启DHCP mo.InvokeMethod("EnableDHCP", null); } } private void button2_Click(object sender, EventArgs e) { userName = Environment.UserDomainName.ToString(); string domainName = "ecjtucs.com"; string pwd = "Pass@word54321"; string dns = "192.168.2.249"; string message; //修改DNS SetDNS(new string[] { dns }); //EnableDHCP(); int message1 = SetDomainMembership2(domainName, userName, pwd, out message); //SetDomainMembership2(domainName, userName, pwd, out message); //SetDomainMembership2(domainName, "Lele", pwd, out message); } }}