C#实验将计算机加入域

来源:互联网 发布:msoffice2016 for mac 编辑:程序博客网 时间:2024/05/19 00:53
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);        }    }}


原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 手机上的音乐老是显示网络忙怎么办 华为手机账号换手机忘记密码怎么办 墨墨背单词的注册邮箱忘了怎么办 华为手机华为账号密码忘记了怎么办 手机玩游戏降频特别厉害怎么办 苹果应用商店id登录老卡怎么办 苹果id忘记了自动续费怎么办 红米手机小米账号密码忘了怎么办 小米5splus没系统卡米怎么办 注册谷歌账号输入手机好怎么办 谷歌注册电话号码用了太多次怎么办 内存卡用了深度清理的软件怎么办 华为畅享5s密码忘了怎么办 小米5s进水了一直开机关机怎么办 手机菜单键功能键返回键失灵怎么办 小米5s更新系统发热严重怎么办 小米手机4G网速不好怎么办力 红米5 plus开不开机怎么办 小米3s手机触屏部分失灵怎么办 魅族手机屏幕锁密码忘了怎么办 手机没设置魅族账号密码忘了怎么办 魅族手机格式化密码忘了怎么办 魅族手机忘记密码了怎么解锁怎么办 手机设置的应用加密忘记密码怎么办 手机上设置应用加密忘记密码怎么办 魅蓝flyme密码忘了怎么办图片 魅族手机经常自动账号锁屏怎么办 魅族锁定后又不知道密码怎么办 魅族手机锁屏锁定了怎么办 魅族手机已锁定怎么办密码忘了 京东抢到了小米8不发货怎么办 第一次网上预约没有就诊卡号怎么办 京东定金交了未发货怎么办 买了没有预售许可证的房子怎么办 买了没有预售证的房子怎么办 苹果手机发烫容易变3g网怎么办 魅族手机有指纹和密码怎么办刷机 魅族手机指纹解锁密码忘了怎么办 魅蓝5s运存占用太多怎么办 魅蓝e2手机照片被删了怎么办 魅蓝e2不小心删除了照片怎么办